将可分割对象从片段传递给活动

时间:2016-10-27 01:42:51

标签: android android-fragments android-activity

我有一个片段MyFragment

public class MyFragment extends Fragment {
    //Some code here like to constructor

    //Trying to pass an object to another Activity
    Intent i = new Intent(getActivity(), NextActivity.class);
    startActivity(i);
    i.putExtra("test",  parcableObject);
    getActivity().finish();
}

我有一项活动NextActivty

public class NextActivity extends AppCompatActivity {
    //Some code here like to constructor
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next_activity);

        Intent intent = getIntent();
        mBoard =  intent.getParcelableExtra("test");
        Log.d(TAG, "onCreate: " + mBoard);
}

这是我的Board班级

public class Board implements Parcelable {
    //Implements all the Parcelable methods.
    protected Board(Parcel in) { 
        //Auto-generated code here
    }
    public static final Creator<Board> CREATOR = new Creator<Board>() {
        //Auto-generated code here
    }
    @Override
    public int describeContents() {
        //Auto-generated code here
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //Auto-generated code here
    }
}

我的mBoard总是null

我有没有在这里做的事情?

1 个答案:

答案 0 :(得分:2)

你把你的额外错误的顺序。在开始活动之前先把它放好。

public class MyFragment extends Fragment {
    //Some code here like to constructor

    //Trying to pass an object to another Activity
    Intent i = new Intent(getActivity(), NextActivity.class);
    i.putExtra("test",  parcableObject);
    startActivity(i);
    getActivity().finish();
}