Android如何通过intent在2个不同的活动中传递2个片段之间的变量

时间:2017-07-27 17:21:38

标签: android variables android-activity fragment bundle

现在我有2个不同的活动,叫做MainControl(有3个片段)和MainControl2(有2个片段)。我想将变量从Maincontrol中的1st Fragment传递到MainControl2中的1st Fragment。

以下是我用来实现此目的的代码: -

MainControl 1st Fragment

@Override
    public void openPostDescription(Data2 data2) {
        Intent intent = new Intent(getActivity(), MainControl2.class);
        intent.putExtra("title", data2.getTitle());
        intent.putExtra("comment", data2.getNumComments());
        intent.putExtra("domain", data2.getDomain());
        intent.putExtra("author", data2.getAuthor());
        intent.putExtra("image", data2.getUrl());
        intent.putExtra("score", data2.getScore());
        intent.putExtra("ups", data2.getUps());
        startActivity(intent);
    }

MainControl2.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_control2);

        Bundle bundle = getIntent().getExtras();
        PostDescription postDescription = new PostDescription();
        postDescription.setArguments(bundle);

        toolbar = (Toolbar)findViewById(R.id.mainControl2Toolbar);
        setSupportActionBar(toolbar);



        tabLayout = (TabLayout)findViewById(R.id.mainControl2TabLayout);
        viewPager = (ViewPager)findViewById(R.id.mainControl2ViewPager);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        viewPagerAdapter.addFragments(new PostDescription(), "DESCRIPTION");
        viewPagerAdapter.addFragments(new PostComments(), "COMMENT");

        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }

MainControl2 1st Fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_post_description, container, false);

    String title = getArguments().getString("title");


    return v;
}

我得到的错误是空对象引用中的标题。我无法弄清楚它在什么阶段导致这种中断,是否有我遗漏的东西?

1 个答案:

答案 0 :(得分:0)

在MainControl2的第一个片段中。写 getActivity().getIntent().getStringExtra("title");

所以你的最终片段代码变成了:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_post_description, container, false);

    String title = getArguments().getString("title");


    return v;
}

您已使用getArguments().getString("title");返回创建片段时传递的参数。

详细了解如何使用getArguments()setArguments() here