pat*_*pat 2 java android listadapter custom-adapter
我对android有点新,我正试图弄清楚这些自定义列表适配器.所以我有一个扩展BaseListActivity的活动和一个类似的函数:
public void inflate(){
ArrayList<String> words = new ArrayList<String>();
orders.add("hello");
orders.add("world");
wordsList = (ListView) findViewById(R.id.list);
WordsAdapter adapter = new WordsAdapter(this, R.layout.single_word_container_item,words);
wordsList.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)
然后我按如下方式实现我的自定义WordsAdapter:
public class WordsAdapter extends ArrayAdapter<String>{
public Context context;
public ArrayList<String> _words;
//not sure the purpose of 'a' here
public WordsAdapter(Context context, int a, ArrayList<String> words) {
super(context, a, words);
_words = words;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.single_word_container_item, null);
TextView wordName = (TextView) findViewById(R.id.wordName);
if(!_words.isEmpty()){
wordName.setText(_word.remove(0));
}
return v;
}
}
Run Code Online (Sandbox Code Playgroud)
从我从日志中可以看出,getView永远不会被调用.'single_word_container_item'只是一个xml文件,其布局我想多次膨胀.我不确定整个过程 - 我想你在listview上设置了一个适配器,然后在那个适配器中你负责显示每次实际显示的内容,那么我在这里做错了什么?目前我得到一个空指针异常,我设置我的适配器,但早些时候它只是不会显示任何东西.日志显示它进入WordsAdapter构造函数但随后死亡.提前感谢任何建议.
编辑:所以在我的xml中识别listview似乎有些不对劲.
如果您使用:
ListView
android:id="@+id/android:list" OR android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ListView
Run Code Online (Sandbox Code Playgroud)
使用它时,错误是空指针异常
但如果你把它定义为:
ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ListView
Run Code Online (Sandbox Code Playgroud)
你得到错误:07-15 19:18:50.240:E/AndroidRuntime(29842):引起:java.lang.RuntimeException:你的内容必须有一个ListView,其id属性是'android.R.id.list'
编辑:显然你不能扩展listactivity并调用setcontentview().由于我需要在列表视图之上的视图,我不想扩展列表活动,而是调用setcontentview并只通过其id引用列表.
现在我的错误是:
java.lang.IllegalStateException:适配器的内容已更改,但ListView未收到通知.确保不从后台线程修改适配器的内容,而只是从UI线程修改.
我尝试在setAdapter()之后调用adapter.notifyDataSetChanged(),但似乎没有用.我应该把它叫到其他地方吗?
你的getView()方法有一个错误:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v;
if (convertView == null) {
v = inflater.inflate(R.layout.single_word_container_item, null);
} else {
v = convertView;
}
TextView wordName = (TextView) v.findViewById(R.id.wordName);
// questionable logic
if(!_words.isEmpty()){
wordName.setText(_word.remove(0));
}
return v;
}
Run Code Online (Sandbox Code Playgroud)
必须在行的视图上调用findViewById().
还要看一下上面可疑的逻辑,你想做什么?如果要直接从适配器中删除listview对象,这将无法正常工作.
| 归档时间: |
|
| 查看次数: |
11362 次 |
| 最近记录: |