How to clear ListView on Fragment when back button pressed?

旧街凉风 提交于 2019-12-02 11:17:37

问题


All data from that ListView is provided by a CursorAdapter. Whenever I pressed back button and return to activity, then click on the activity to start my fragment, all previous data still there stacking on top of each other.


回答1:


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.




回答2:


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



回答3:


When returned to the activity after pressing back button call:

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



回答4:


you can try

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

        }


来源:https://stackoverflow.com/questions/47626321/how-to-clear-listview-on-fragment-when-back-button-pressed

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