0

Есть класс для ArrayList ItemClass. Есть ArrayList nomenclatureList, созданный в onCreate.

ArrayList<ItemClass> nomenclatureList = new ArrayList<>();

Хочу использовать Collections.sort(nomenclatureList) за пределами onCreate (внутри onCreate он прекрасно работает).

Если конкретно - хочу использовать Collections.sort(nomenclatureList) в контекстном меню:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_filter, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch(id) {
            case R.id.alexeevskoe:
                Intent alexeevskoeMK = new Intent(ItemsListMK.this, AlexeevskoeMK.class);
                startActivity(alexeevskoeMK);
                break;
            case R.id.gustiyar:
                Intent gustiyarMK = new Intent(ItemsListMK.this, GustiyarMK.class);
                startActivity(gustiyarMK);
                break;
        }
        return true;
    }

Код onCreate:

setContentView(R.layout.nomenclature_list);
nomenclatureList.add(new ItemClass(

[...]

ItemAdapter adapter = new ItemAdapter(this, nomenclatureList);
ListView listView = findViewById(R.id.nomenclature_list);
listView.setAdapter(adapter);

Что мне необходимо использовать? Недавно в java и android, вероятно мой вопрос нубский, но не могу разобраться.

1 ответ 1

1

Объявить nomenclatureList глобально в теле класса вашей Activity.

public class  MyActivity extends Activity {

     ArrayList<ItemClass> nomenclatureList = new ArrayList<>();
     ItemAdapter adapter;
     public void onCreate(...) {
          // что-то делаем с nomenclatureList 

          setContentView(R.layout.nomenclature_list);
          nomenclatureList.add(new ItemClass());

          [...]

          adapter = new ItemAdapter(this, nomenclatureList);
          ListView listView = findViewById(R.id.nomenclature_list);
          listView.setAdapter(adapter);
     }

    public boolean onOptionsItemSelected(MenuItem item) {
        Collections.sort(nomenclatureList);
        adapter.notifyDataSetChanged(); 
        int id = item.getItemId();
        switch(id) {
            case R.id.alexeevskoe:
                Intent alexeevskoeMK = new Intent(ItemsListMK.this, AlexeevskoeMK.class);
                startActivity(alexeevskoeMK);
                break;
            case R.id.gustiyar:
                Intent gustiyarMK = new Intent(ItemsListMK.this, GustiyarMK.class);
                startActivity(gustiyarMK);
                break;
        }
        return true;
    }
}
1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.