更改某些ListView项目的文本

时间:2014-05-28 16:12:20

标签: android android-listview baseadapter getview

我知道有多个ListView项目具有强大的列表视图,可以显示可爱的标题。

但是,我不需要这么复杂。我只需要在某些列表项上方插入一个简单的TextView。所以我尝试在getView

BaseAdapter方法中执行此操作
public View getView(final int position, View convertView, final ViewGroup parent) {

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listitem, null);

            //set title accordingly
            if (position == 0 ) {
                //insert some text here
            }

            Log.d(TAG, "getView position = " + position);
        }

        TextView txt = (TextView) convertView.findViewById(R.id.sometextview);        
        txt.setText("some text comes here");

        return convertView;
    }

但是,虽然此代码只应更改第一个项目的文本,但它也会随机更改其他项目的文本。列表中有20个项目。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您忽略了视图回收 - 当您滚动时,您添加文本的特定视图正在列表中使用,因为它已被回收。

你应该做的是

if (position == 0 ) {
    //add the text
} else {
    //remove the text
}

为了澄清,您应该在convertView == null if语句之外执行此操作 - 它应该在每个getView上执行,而不仅仅是在创建新视图时。

编辑:想想看,如果您只需要第一项上方的文字,为什么不使用

listView.addHeaderView(v);

它可能会为您提供所需的信息。

答案 1 :(得分:0)

ListView项目被回收。您无法手动编辑项目,您必须编辑代表该项目的数据。您的适配器应该包含一些可以在外部修改的数据类型,然后通过调用notifyDatasetChanged()列表视图将适当地重新绘制。

Sudo代码:

class MyData {

    String normalText;
    String overrideText;

}

....

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

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.listitem, null);

        //set title accordingly
        if (position == 0 ) {
            //insert some text here
        }

        Log.d(TAG, "getView position = " + position);
    }

    MyData data = getItem(position);

    TextView txtExtra = (TextView) convertView.findViewById(R.id.extratextview);
    txtExtra.setVisibility(data.overrideText == null ? View.GONE : View.VISIBLE);
    txtExtra.setText(data.overrideText == null ? "" : data.overrideText);

    TextView txt = (TextView) convertView.findViewById(R.id.sometextview);        
    txt.setText(data.normalText);

    return convertView;
}