android - 重写 Android ArrayAdapter

标签 android listview android-arrayadapter

我想做一件很简单的事情。我的应用程序中有一个 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/

相关文章:

Android,如何在相对布局中设置带有百分比的 ImageView

android - 我需要在 Xamarin Forms 按钮内设置格式化文本(两种不同大小)

android - 为一行中的按钮自定义 arrayadapter 和 onclicklistener

java - 不跳转地更改 ListView

android - 设置 ListView 的最大可见行数

Android OnSystemUiVisibilityChangeListener 仅在纵向模式下触发

android - ListView inside ScrollView 滚动改进

java - ListView 随时间更新

wpf - 当存在基于触发器隐藏显示元素的复杂数据模板时,我的 ListView 或 ListBox 控件大小不会缩小?

android - 数组适配器 notifyDataSetChanged() 将不起作用