无法在自定义适配器中按 ID 引用布局对象



我正在尝试创建自定义对象适配器,部分代码需要通过其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"是肯定定义的。

我做错了什么?

您需要以这种方式膨胀布局:

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

然后你可以找到视图:

convertView.findViewById(R.id.someid);

使用 "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;
}

此外,还必须使用持有人模式重用视图,以获得更好的 ListView 性能。

最新更新