我正在尝试创建自定义对象适配器,并且部分代码需要通过其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”是明确定义的。
我做错了什么?
答案 0 :(得分:2)
您需要以这种方式扩充您的布局:
LayoutInflater li = LayoutInflater.from(getContext());
convertView = li.inflate(R.layout.yourlayoutid, null);
然后你就可以找到观点了:
convertView.findViewById(R.id.someid);
答案 1 :(得分: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性能。