我的自定义适配器(安卓)怎么了?



我为ListView制作了一个适配器,如下所示:

SimpleAdapter adapter = new SimpleAdapter(this.getBaseContext(), listItem, R.layout.list_cell_icon, new String[] { "img", "title", "description" }, new int[] { R.id.img, R.id.title, R.id.description }) {
        @Override
        public boolean isEnabled (int position) {
            if(position == 1 || position == 2) {
                return false;
            }
            return true;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            if(position == 1 || position == 2) {
                TextView tv = (TextView) v.findViewById(R.id.title);
                tv.setTextColor(Color.DKGRAY);
            }
            return v;
        }
    };

现在我有两个项目,我想在列表中禁用,然后我想显示深灰色的文本。我的问题是,第0行的文本颜色也变为深灰色。怎么可能呢?我错过什么了吗?

您需要添加以下内容:

TextView tv = (TextView) v.findViewById(R.id.title);    
if(position == 1 || position == 2) {
    tv.setTextColor(Color.DKGRAY);
} else {
    tv.setTextColor(Color.WHITE);
}

原因是getView被调用了几次,而不是按照特定的顺序调用,并且getView回收视图。因此,您的TextView对象很可能始终是同一个对象。因此,您必须将颜色设置回视图。或者,您可以使用一个状态和一个选定的(如TextView上的setEnabled(false))

最新更新