我有一个包含一些数据的ListFragment。我试图根据我从菜单中选择的项目对列表的内容进行排序。当我从菜单中选择一个选项时,如何更新列表的内容?我不想创建另一个片段,我只想按名称或按日期对列表中的信息进行排序,因此当我单击菜单中的一个项目时,列表会立即更新,具体取决于我是否单击排序依据按日期命名或排序。
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_sort_by_name) {
Fragment currentFragment = this.getFragmentManager().findFragmentById(R.id.fragment1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.Months, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
}
return super.onOptionsItemSelected(item);
}
然后我有片段的java类:
public class EventsListFragment extends ListFragment implements OnItemClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:0)
使用Sort(通过比较器)或通过Filter on array或自定义适配器 - 取决于适配器对象的复杂性
一些例子和参考文献:
数组适配器的基本示例:
Adapter.sort(new Comparator<Item>() {
@Override
public int compare(Item lhs, Item rhs) {
return lhs.compareTo(rhs); //Your sorting algorithm
}
});
* Item - 适配器项的类定义
数组适配器doc ref:
完整的案例解决方案: