3个片段之间的通信

时间:2017-06-20 08:20:20

标签: android android-fragments

我有3个片段。片段A,B和C. A有一个"继续"将它带到B的按钮.B有一个继续按钮,它将把它带到C.C有一个"添加"按钮将把它带回B.现在我想按下继续按钮时将数据从A发送到B.按下添加按钮时也从C到B.我尝试过使用bundle。它是第一次从A转到B时给出空指针异常,C中的包是空的。怎么解决这个?任何帮助都非常感谢。请仔细阅读下面的代码段

注意:ItemDetails从片段A获得,EmployeeDetails从片段C获得.Fragment Flow => 1.片段A 2. A到B(itemsList传递给B)3。B到C(无通信)4。从C返回B(员工列表传递给B)。

 String TEMP_STRING_EMPLOYEES, TEMP_STRING_ITEMS;
EmployeeList employeeList;
ItemsList itemsList;

@Override
public void onStart() {
    super.onStart();
    Bundle args = getArguments();
    if (args != null) {

        TEMP_STRING_ITEMS = args.getString("ItemsDetails");

        try {
            // Set article based on argument passed in
            TEMP_STRING_EMPLOYEES = args.getString("EmployeeDetails");

        } catch (NullPointerException ex) {

        }


    } else {

    }

}
//Next lines of code from MAinActivity.java

@覆盖     public void onFragmentInteractionForEmployeeDetails(ArrayList arrayList){

    EmployeeList employeeList = new EmployeeList(arrayList);
    String correspondingJson = NavigationUtils.getStringForObject(employeeList);

    B newFragment = new B();
    Bundle args = new Bundle();
    args.putString("EmployeeDetails", correspondingJson);
    newFragment.setArguments(args);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

1 个答案:

答案 0 :(得分:0)

您可以在片段中使用回调,而活动会存储您的对象。

<强>活动

public class MyActivity extends Activity implements MyActivityCallback{

    private Object myObject; // Replace with your object type

    @Override 
    public Object getMyObject(){
         return myObject;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myObject = new Object();
        // ...
    }

    // ....
}

<强> MyActivityCallback

public interface MyActivityCallback{
   Object getMyObject();
}

<强>片段

private MyActivityCallback mCallback;

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {
        mCallback = (MyActivityCallback) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement " + MyActivityCallback.class.getSimpleName());
    }
}

@Override
public void onDetach() {
    mCallback = null;
    super.onDetach();
}

然后在您的片段中,要访问您的对象,请执行mCallback.getMyObject();