Android - problems using FragmentActivity + Loader to update FragmentStatePagerAdapter

后端 未结 3 1127
鱼传尺愫
鱼传尺愫 2020-12-29 07:30

I\'m trying to use FragmentActivity with ViewPager to display dynamic list of Fragments. There are plenty of examples on how to do a s

3条回答
  •  时光说笑
    2020-12-29 08:19

    I had a very similar problem to this and solved it by using a handler on the Fragment.

    I wanted to show an alert dialog on onLoadFinished(), similar to the following

    public class MyFragment extends Fragment 
        implements LoaderManager.LoaderCallbacks {
    
        public void onLoadFinished(Loader loader, T data) {
            showDialog();
        }
    
        public void showDialog() {
            MyAlertDialogFragment fragment = new MyAlertDialogFragment();
            fragment.show(getActivity().getSupportFragmentManager(), "dialog");
    
        }
    }
    

    But this gave an error

    can not perform this action inside of onLoadFinished

    The solution was to add a handler to the fragment to take care of showing the dialog

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == MSG_SHOW_DIALOG) {
                showDialog();
            }
        }
    };
    

    And then modify onLoadFinished(...) to send a message to the handler instead

       public void onLoadFinished(Loader loader, T data) {
            handler.sendEmptyMessage(MSG_SHOW_DIALOG);
        }
    

提交回复
热议问题