当触发onItemClick时,我的代码确实更新了ListView,但只有在onItemClick方法中替换了行""
categoryAdapter.notifyDataSetChanged();
行
lv.setAdapter(new CategoryAdapter(categories));
我应该如上所示更换线路,还是应该使用notifyDataSetChanged?因为文档说它也应该更新视图。
此外,当我这样做时,应用程序会运行,但是按下后退按钮会关闭应用程序,而不是返回到我希望看到的最后一个屏幕。
public class MainActivity extends ActionBarActivity {
ListView lv;
String[] categories = null;
private static String[] failCategories = {"a","b","c};
private static String[] category_a= { "a1","a2"};
CategoryAdapter categoryAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
lv = (ListView) findViewById(R.id.lvCategories);
categories = failCategories; //initial set
categoryAdapter = new CategoryAdapter(categories);
lv.setAdapter(categoryAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
categories = category_a;
categoryAdapter.notifyDataSetChanged();
}
}
});
}
private class CategoryAdapter extends ArrayAdapter<String>{
CategoryAdapter(String[] objects) {
super(getBaseContext(), R.layout.activity_categories,R.id.tvCategory, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
return convertView;
}
}
}
答案 0 :(得分:0)
如果您只想更新尊重的项目,请在代码中尝试此部分代码,确保category_a具有相同的项目
版本1
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
categoryAdapter.insert(position,category_a[position]);
categoryAdapter.notifyDataSetChanged();
}
版本2 如果你想用category_a中的所有项目更新整个列表视图,那么
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
categoryAdapter.clear();
categoryAdapter.addAll(category_a);
categoryAdapter.notifyDataSetChanged();
}