gpt4 book ai didi

Android 按字母顺序对 ListView 进行排序

转载 作者:IT王子 更新时间:2023-10-28 23:28:32 47 4
gpt4 key购买 nike

所以我正在尝试为 ListView 排序一个简单的 ArrayAdapter。这是我尝试过的:

ListView lv;
String[] months = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};

ArrayAdapter<String> adapter;
ArrayList<String> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

lv = (ListView) findViewById(R.id.listView1);
lv.setFastScrollEnabled(true);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, months);
lv.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub

switch (item.getItemId()) {
case R.id.sortasc:
list = new ArrayList<String>(Arrays.asList(months));
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
adapter.clear();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
return true;
case R.id.sortdesc:

return true;
default:
return super.onOptionsItemSelected(item);
}
}

但是我得到 UnsupportedOperationException,这是怎么回事?我真的需要帮助。提前致谢!

最佳答案

在对项目进行排序后,您没有调用 setAdapter(adapter)。

像下面这样使用

adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();

而不是

adapter.clear(); // Useless 
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();

关于Android 按字母顺序对 ListView 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19676781/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com