2011-04-11 97 views
0

我在为图库上的项目编写自定义适配器时遇到了问题。我遵循android开发人员网站上的步骤,但不是返回一个ImageView,而是返回一个TextView。但是,当我尝试运行该应用程序时,我尝试将子项添加到库时遇到ClassCastException。图库的自定义适配器

但是,如果我使用基本字符串适配器的图库它的作品,如果我使用ImageView它也可以。我不知道这个问题,因为方法

@Override 
public View getView(int position, View convertView, ViewGroup parent) 

返回一个View,它是ImageView和TextView的基类。所以我不会发生什么可能的错误。你知道可能是什么原因造成的问题?

非常感谢

这是适配器的代码,

public class HistoryIndexAdapter extends BaseAdapter { 

private Context context; 
private ArrayList<History> historyIndex; 
private Typeface typeface; 

public HistoryIndexAdapter(Context context, ArrayList<History> historyItems) { 

    this.context = context; 
    this.historyIndex = historyItems;  
    this.typeface = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.font)); 
} 

@Override 
public int getCount() { 
    return historyIndex.size(); 
} 

@Override 
public Object getItem(int position) { 
    return position; 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 


    TextView item = new TextView(context); 


    item.setText(historyIndex.get(position).getDate()); 
    item.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    item.setTypeface(typeface); 
    item.setTextColor(R.color.white); 

    return item; 
} 

}

回答

0

什么是您使用的是完全合格的LayoutParams类?你需要使用Gallery.LayoutParams。如果你不这样做,你会得到一个ClassCastException。

+0

谢谢詹姆斯,其实这是问题;进口并不正确。现在它完美了,非常感谢,我不会发现这个错误太快嘿嘿 – lblasa 2011-04-11 17:19:13