How to clear ListView on Fragment when back button pressed?

假如想象 提交于 2019-12-02 04:41:24

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.

HaroldSer

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

When returned to the activity after pressing back button call:

arraylist.clear();
adapter.notifyDataSetChanged();

you can try

      try {
           arraylist.clear();
           listView.removeAllViews();
        }catch (Exception e){

        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!