Android:按下后退按钮时刷新上一个片段数据

时间:2013-04-18 11:06:51

标签: android performance

我有2个片段,片段A和片段B.我通过使用FragmentTransaction().add在片段A上添加片段B,这意味着片段A是片段B的底层。有没有办法改变数据片段A我在Fragment B上做了什么并按下片段B中的后退按钮?我希望有一种通用方式来通知片段A.因为它可能是另一个片段被覆盖。我尝试使用FragmentTransaction.replace() - 它可以正常刷新上一页。

1 个答案:

答案 0 :(得分:4)

只需覆盖您的活动和片段中的onBackPressed(),然后在那里进行必要的调用。

更多回调/与其他片段的通信可以在这里找到:

Communicating with Other Fragments

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
        }
    }
}