Tek*_*ebo 8 android listview android-layout android-xml android-adapter
我正在考虑编写一个自定义适配器来填充列表视图,每行3个textview.我已经找到了相当多的示例代码来执行此操作,但看起来最好的代码是:http://www.anddev.org/custom_widget_adapters-t1796.html
经过一些小的调整来修复最新的Android SDK的一些编译器问题后,我让它运行,只是为了得到异常:
ERROR/AndroidRuntime(281):java.lang.UnsupportedOperationException:AdapterView不支持addView(View,LayoutParams)
所以我做了很多研究,发现了很多可能的原因和解决方法.这些都没有改变.我的适配器代码目前是:
public class WeatherAdapter extends BaseAdapter {
private Context context;
private List<Weather> weatherList;
public WeatherAdapter(Context context, int rowResID,
List<Weather> weatherList ) {
this.context = context;
this.weatherList = weatherList;
}
public int getCount() {
return weatherList.size();
}
public Object getItem(int position) {
return weatherList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Weather weather = weatherList.get(position);
//LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.weather_row, null, true);
TextView cityControl = (TextView)v.findViewById( R.id.city );
TextView temperatureControl = (TextView)v.findViewById( R.id.temperature );
ImageView skyControl = (ImageView)v.findViewById( R.id.sky );
return v;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我已经尝试了注释的方式获得inflater,并且目前没有注释掉.我已经尝试将"父"传递给inflate以及null,并传递"true","false"并完全省略最后一个参数.他们都没有工作,到目前为止我发现的所有例子都是从2008年开始的,我觉得这种感觉有点过时了.
如果有人可以帮助解决这个问题,那么我很乐意解决这个问题.
小智 16
我相信这条线是错的:
View v = inflater.inflate(R.layout.weather_row, null, true);
Run Code Online (Sandbox Code Playgroud)
你需要:
View v = inflater.inflate(R.layout.weather_row, parent, false);
Run Code Online (Sandbox Code Playgroud)
false使得膨胀的视图独立于父级,而不是附加到父级,这非常奇怪地似乎是AdapterViews中自定义视图的可接受设计.为什么会这样,我觉得完全莫名其妙,但上面的模式对我有用.
我也是初学者也是如此,所以请用一点点盐来回答这个问题 - 如果它不起作用,继续前进,谷歌会更多.不熟悉,AdapterView因为我传统上有一个ListView或GridView一个自定义适配器扩展了一个BaseAdapter然后listView.setAdapter(myCustomAdapter).
你可以尝试在WeatherAdapter课堂上制作这样的东西:
public void addToList(Weather mWeather) {
weatherList.add(mWeather);
}
Run Code Online (Sandbox Code Playgroud)
然后在调用的类中WeatherAdapter:
weatherAdapter.addToList(weatherToAdd);
weatherAdapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)
您还需要在getView方法中进一步优化它:
http://www.youtube.com/watch?v=wDBM6wVEO70
| 归档时间: |
|
| 查看次数: |
16000 次 |
| 最近记录: |