Android:按下向后按钮时刷新以前的片段数据

Nai*_*eBz 4 performance android

我有2个片段,分别是片段A和片段B。我通过使用FragmentTransaction().add,在片段A之上添加了片段B ,这意味着片段A位于片段B的基础上。 B,然后按“ 片段B”中的“ 返回”按钮?我希望有一种通用的方式来通知片段A。因为它可能是另一个被覆盖的片段。我尝试使用FragmentTransaction.replace()-刷新前一页效果很好。

Osc*_*rEi 6

只需覆盖onBackPressed()您的活动和片段,然后在其中进行所需的调用即可。

有关回调/与其他片段的通信的更多信息,请参见此处:

与其他片段通信

public class FragmentA extends Fragment {
    public void updateMyself(String updateValue){
        Log.v("update", "weeee Fragment B updated me with" + updateValue);
    }
}

public class FragmentB extends Fragment {

    public Interface FragmentBCallBackInterface {
        public void update(String updateValue);
    }

    private FragmentBCallBackInterface mCallback;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mCallback = (FragmentBCallBackInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement FragmentBCallBackInterface");
        }
        //As an example we do an update here - normally you wouln't call the method until your user performs an onclick or something 
        letsUpateTheOtherFragment();
    }

    private void letsUpateTheOtherFragment(){
        mCallback.update("This is an update!);
    }
}


public class MyActivity extends Activity implements FragmentInterfaceB {

    @Override
    public void update(String updateValue){
          FragmentA fragmentA = (FragmentA) getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (fragmentA != null) {
            fragmentA.updateMyself(updateValue);
        } else {
            //replace the fragment... bla bla check example for this code
        }
    }
}
Run Code Online (Sandbox Code Playgroud)