代码很简单,我只想看看如何用全新的数据更新listview。我将值存储在数组中并将其传递给arrayadapter。单击列表视图项时,我想清除现有列表视图并添加一组新值并在列表视图中显示新项。
我可以看到数组正在使用新值进行更新,但即使在调用notifyDataSetChanged()之后也不会显示这些值。请看一下代码,让我知道我在这里做错了什么。提前谢谢。
public class MainActivity extends Activity {
public ListView mListView;
String[] stringArray;
string[] stringArray1;
String[] stringArray2;
String[] stringArray3;
String[] stringArray4;
static int track=1;
public ArrayAdapter<String> adapter;
public ArrayList<String[]> aList;
static Iterator<String[]> aitr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView=(ListView) findViewById(R.id.listView1);
//stringArray= new String[4];
stringArray1 = new String[] {"Bright Mode1", "Normal Mode1","silly mode1", "dupe mode1","trail mode1"};
stringArray2 = new String[] { "Bright Mode2", "Normal Mode2","silly mode2", "dupe mode2","trail mode2"};
stringArray3 = new String[] { "Bright Mode3", "Normal Mode3","silly mode3", "dupe mode3","trail mode3"};
stringArray4 = new String[] { "Bright Mode4", "Normal Mode4","silly mode4", "dupe mode4","trail mode4"};
aList=new ArrayList<String[]>();
aList.add(stringArray2);
aList.add(stringArray3);
aList.add(stringArray4);
aitr=aList.iterator();
stringArray=stringArray1;
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
mListView.setAdapter(adapter);
}
public void updateArray(){
if(aitr.hasNext()){
mListView.clearChoices();
stringArray=aitr.next();
}
}
@Override
protected void onStart(){
super.onStart();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int a = view.getId();
Log.e("devsample", "the is is: " + a + ", " + position + ", " + id);
updateArray();
adapter.notifyDataSetChanged() ;
}
});
}
}
答案 0 :(得分:1)
在updateArray()
方法中,您为stringArray
分配了新数组,但您的adapter
仍然引用了旧版stringArray
。
在updateArray()
的末尾添加以下两行,以更新adapter
:
adapter.clear();
adapter.addAll(stringArray); // or if you're targeting Android < 11 call: adapter.add() in a loop
答案 1 :(得分:0)
所以我在发表的帖子Unable to modify ArrayAdapter in ListView: UnsupportedOperationException
中将问答者的答案和st0le提供的解释混合在一起解决了这个问题。