编辑listView内容 - Android

时间:2012-12-12 12:51:05

标签: android listview android-listview textview android-arrayadapter

我将自定义ArrayAdapter设置为listView。在listView的每个元素里面,我有一个与我创建的.xml相匹配的项目。代码如下所示:

listContent.xml

<RelativeLayout
[... some code ommited]
    <ImageView
    [...]
    <TextView
    android:id="@+id/listViewText"
    [...]

自定义数组适配器getView(int position,View convertView,ViewGroup parent)

if (position < 4)
{
    convertView = inflater.inflate(R.layout.listContent,null);

    TextView tv = (TextView) findViewById(R.id.listViewText);

    tv.setTextSize(18);
    if (position == 0) tv.setText("0");
    else if (position == 1) tv.setText("1");
    else if (position == 2) tv.setText("2");
    else if (position == 3) tv.setText("3");

    return convertView;
}
return null;

我似乎无法让这个工作,我总是得到一些错误。为了编辑listView项目中的TextView,我需要做什么?

2 个答案:

答案 0 :(得分:1)

将自定义数组适配器getView代码更改为:

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

 View row = convertView;

 if(row==null){
  LayoutInflater inflater=getLayoutInflater();
  row=inflater.inflate(R.layout.listContent, parent, false);
 }

 TextView tv=(TextView)row.findViewById(R.id.listViewText);


tv.setTextSize(18);
    if (position == 0) tv.setText("0");
    else if (position == 1) tv.setText("1");
    else if (position == 2) tv.setText("2");
    else if (position == 3) tv.setText("3");

 return row;
}

答案 1 :(得分:1)

更改

TextView tv = (TextView) findViewById(R.id.listViewText);

TextView tv = (TextView) convertView.findViewById(R.id.listViewText);

并删除此

if (position < 4)