2

我正在尝试创建一个自定义对象适配器,并且部分代码需要通过其 ID 引用对象。但是,我收到错误说 ID 不存在:

private static class GeoAreaAdapter extends BaseAdapter implements Filterable{
    private LayoutInflater mInflater;   
    private int resource;
    private GeoArea _myGeoArea;
public GeoAreaAdapter(Context context, int resource, GeoArea myGeoArea) {
    mInflater = LayoutInflater.from(context);
    _myGeoArea = myGeoArea;
}
public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout GeoAreaView;
    if (GeoAreaView == null) { 
        GeoAreaView = new LinearLayout(mInflater.getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater)mInflater.getContext().getSystemService(inflater);
        vi.inflate(resource, GeoAreaView, true);
    }
    else {
        GeoAreaView = (LinearLayout) convertView;
    }

    TextView name = (TextView) convertView.findViewById(R.id.txtGeoAreaName);
    name.setText(_myGeoArea.name);

    return convertView;
}
....
}

它发生在“R.id.txtGeoAreaName”中。

这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/txtGeoAreaName" />

</LinearLayout>

如您所见,“txtGeoAreaName”是明确定义的。

我究竟做错了什么?

4

2 回答 2

2

您需要以这种方式扩充您的布局:

LayoutInflater li = LayoutInflater.from(getContext());
convertView = li.inflate(R.layout.yourlayoutid, null);

然后你可以找到视图:

convertView.findViewById(R.id.someid);
于 2013-11-08T02:46:17.127 回答
0

使用“txtGeoAreaName”作为TextView的id属性

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/txtGeoAreaName" />
</LinearLayout>

更新getView方法如下

public View getView(int position, View convertView, ViewGroup parent) {     
    if (convertView == null) { 
        convertView = mInflater.inflate(resource, GeoAreaView, true);
    }
    TextView name = (TextView) convertView.findViewById(R.id.txtGeoAreaName);
    name.setText(_myGeoArea.name);
    return convertView;
}

此外,您必须使用Holder Pattern来重用视图以获得更好的 ListView 性能。

于 2013-11-08T03:06:16.840 回答