Search code examples
androidandroid-listfragment

Update content in ListFragment on menu click


I have a ListFragment with some data. I am trying to sort the content of my list depending on which item I select from the menu. How can I update the content of the list when I select one option from the menu? I don't want to create another fragment, I just want to sort by name or by date the info that I have in the list so when I click one item in the menu the list updates immediately depending on whether I click sort by name or sort by date.

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);
}

And then I have the java class for the fragment:

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();
}

Solution

  • use a Sort (by comparator) or by Filter on array or custom adapter - depending on the complexity of the adapter object

    some examples and references:

    basic example for array adapter:

    Adapter.sort(new Comparator<Item>() {
        @Override
        public int compare(Item lhs, Item rhs) {
            return lhs.compareTo(rhs);   //Your sorting algorithm
        }
    });
    

    *Item - class definition for adapter item

    array adapter doc ref:

    complete solution for your case: