How to clear ListView on Fragment when back button pressed?

前端 未结 4 1882
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 12:53

All data from that ListView is provided by a CursorAdapter. Whenever I pressed back button and return to activity, then c

相关标签:
4条回答
  • When returned to the activity after pressing back button call:

    arraylist.clear();
    adapter.notifyDataSetChanged();
    
    0 讨论(0)
  • 2021-01-21 13:09

    Make public a method in fragment which will clear your list and call that method from its parent activity's On onBackPressed using fragment's instance.

    0 讨论(0)
  • 2021-01-21 13:09

    you can try

          try {
               arraylist.clear();
               listView.removeAllViews();
            }catch (Exception e){
    
            }
    
    0 讨论(0)
  • 2021-01-21 13:25

    1) Create an interface BackPressedListener:

    public interface BackPressedListener {
        void onBackPressed();
    }
    

    2) In your activity, you can override onBackPressed():

    @Override
    public void onBackPressed() {
        List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
        if (fragmentList != null) {
            for(Fragment fragment : fragmentList){
               if(fragment instanceof BackPressedListener){
                   ((BackPressedListener)fragment).onBackPressed();
               }
            }
        }
    }
    

    3) Implement the interface BackPressedListener, on your fragment. You would override the onBackPressed method in your fragment, clear your list containing the elements and then notify the adapter of the changes as below:

       @Override
            public void onBackPressed()
            {
                 arrayList.clear();
                 adapter.notifyDataSetChanged();
                 finish();
            }
    
    0 讨论(0)
提交回复
热议问题