我对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);
然后我按如下方式实现自定义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):引起:java.lang.RuntimeException:你的内容必须有一个其属性为'android.R.id的ListView。列表“
编辑:显然你无法扩展listactivity并调用setcontentview()。由于我需要在列表视图之上的视图,我不想扩展列表活动,而是调用setcontentview并只通过其id引用列表。
现在我的错误是:
java.lang.IllegalStateException:适配器的内容已更改,但ListView未收到通知。确保不从后台线程修改适配器的内容,而只是从UI线程修改。
我尝试在setAdapter()之后调用adapter.notifyDataSetChanged(),但这似乎不起作用。我应该把它叫到其他地方吗?
答案 0 :(得分:5)
你的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;
}
必须在行的视图上调用findViewById()。
另外看看上面可疑的逻辑,你想做什么?如果要直接从适配器中删除listview对象,这将无法正常工作。
答案 1 :(得分:0)
只需使用充气
val dialog = BottomSheetDialog(context,R.style.BottomSheetTheme)
val view = inflate(context,R.layout.otpsent1layout,null)
dialog.setContentView(view)
dialog.show()