Android, How to restart/refresh a fragment from FragmentActivty?

后端 未结 2 938
灰色年华
灰色年华 2020-12-12 01:08

In my FragmentActivity I have a fragment. This fragment loads data from server. I want we user clicks on refresh button then I call a method in fragment and do refreshing pr

2条回答
  •  爱一瞬间的悲伤
    2020-12-12 01:40

    Executing this

    onRefreshSelected = (OnRefreshSelected) MainScreen.this;
    

    you are assigning your activity in onRefreshSelected field, trying to cast it to your interface, but your activity doesn't implement the interface, that's why ClassCastException raised.

    Instead use something like this

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                    case R.id.menu_refresh:
                        CategoryFragment fragment = (CategoryFragment) getFragmentManager()
                            .findFragmentById(R.id.category_fragment);
                        if (fragment != null) {
                            fragment.getData();
                        }
                        return true;
                    default:
                        return super.onOptionsItemSelected(item);
        }
    

    Your activity can call methods in the fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById() or findFragmentByTag().

提交回复
热议问题