根据从片段中单击的按钮,在活动中加载不同的布局

时间:2017-03-29 11:04:11

标签: android

片段中有2个按钮。我想从片段发送意图到Activity并根据点击的按钮加载布局。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

得到了解决方案。传递一个字符串(使用putExtra)来帮助决定要加载哪个布局。

片段代码:

Button button1 = (Button) rootView.findViewById(R.id.id_button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ScrollingDetailsActivity.class);
            intent.putExtra(ScrollingDetailsActivity.EXTRA_DATA,"Button1_pressed");
            (getActivity()).startActivity(intent);
        }
    });

    Button button2 = (Button) rootView.findViewById(R.id.id_button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ScrollingDetailsActivity.class);
            intent.putExtra(ScrollingDetailsActivity.EXTRA_DATA,"Button2_pressed");
            (getActivity()).startActivity(intent);

活动代码:

    final Intent intent = getIntent();
    final String data = intent.getStringExtra(EXTRA_DATA);

    if (data.equals("button1_pressed"))
    setContentView(R.layout.scrolling_details_button1);

    if (data.equals("button2_pressed"))
        setContentView(R.layout.scrolling_details_button2);

谢谢!