我对 android 有点陌生,正在尝试找出这些自定义列表适配器。所以我有一个扩展 BaseListActivity 的 Activity 和一个类似的函数:
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);
然后我按如下方式实现我的自定义 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;
}
}
从日志中我可以看出,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
使用时报错是空指针异常
但是如果你将它定义为:
ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ListView
您收到错误:07-15 19:18:50.240: E/AndroidRuntime(29842): Caused by: java.lang.RuntimeException: 您的内容必须有一个 ListView,其 id 属性为“android.R.id”。列表'
编辑:显然您不能扩展 listactivity 并调用 setcontentview()。因为我需要在 ListView 之上的 View ,所以我不想扩展列表 Activity ,而是调用 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;
}
必须在行的 View 上调用 findViewById()。
再看看上面的可疑逻辑,你想做什么?如果您直接从适配器中删除 ListView 对象,这将不会很好地工作。
关于java - 获取自定义列表适配器以正确膨胀多个线性布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11495990/