我想做一件很简单的事情。我的应用程序中有一个 ListView ,我可以动态地向其中添加文本。但是,在某一点之后,我想更改 ListView 中文本的颜色。因此,我创建了一个定义自定义列表项的 XML,并将 ArrayAdapter 子类化。但是,每当我在我的自定义 ArrayAdapter 上调用 add() 方法时,一个项目确实会添加到 ListView 中,但文本不会放入其中。
这是我的 XML:`
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_content" android:textSize="8pt"
android:gravity="center" android:layout_margin="4dip"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FF00FF00"/>
还有我的 ArrayAdapter 子类:
private class customAdapter extends ArrayAdapter<String> {
public View v;
public customAdapter(Context context){
super(context, R.layout.gamelistitem);
}
@Override
public View getView(int pos, View convertView, ViewGroup parent){
this.v = convertView;
if(v==null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=vi.inflate(R.layout.gamelistitem, null);
}
if(timeLeft!=0) {
TextView tv = (TextView)v.findViewById(R.id.list_content);
//tv.setText(str[pos]);
tv.setTextColor(Color.GREEN);
}
else {
TextView tv = (TextView)v.findViewById(R.id.list_content);
//tv.setText(str[pos]);
tv.setTextColor(Color.RED);
}
return v;
}
}
我确定我做错了什么,但我对 Android 还是有点陌生。
谢谢! `
最佳答案
您需要在getView()
中设置文本。使用 getItem(pos)
获取要设置的值,然后设置它。
public View getView(int pos, View convertView, ViewGroup parent){
this.v = convertView;
if(v==null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=vi.inflate(R.layout.gamelistitem, null);
}
// Moved this outside the if blocks, because we need it regardless
// of the value of timeLeft.
TextView tv = (TextView)v.findViewById(R.id.list_content);
tv.setText(getItem(pos));
if(timeLeft!=0) {
//TextView tv = (TextView)v.findViewById(R.id.list_content);
//tv.setText(str[pos]);
tv.setTextColor(Color.GREEN);
}
else {
//TextView tv = (TextView)v.findViewById(R.id.list_content);
//tv.setText(str[pos]);
tv.setTextColor(Color.RED);
}
return v;
}
此外,是否有理由将 v
存储为成员变量,而不是仅在函数内部?
关于android - 重写 Android ArrayAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5177056/