如何将按钮单击(片段1)上的值传递给onCreateView(片段2)?

时间:2015-03-04 04:46:06

标签: android fragment

我有2 Fragments。 当我点击Fragment 1中的按钮时,我会这样做:

  1. 我设置变量String title = "Lady Gaga"
  2. 我会展示Fragment 2
  3. 显示Fragment 2时,我想显示标题文字。

    怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用捆绑包传递数据:

            Bundle data = new Bundle();
            data.putString("title", "my title");
            Fragment fragment2 = new Fragment2();
            fragment2.setArguments(data);
            FragmentTransaction agm_ft = getSupportFragmentManager()
                    .beginTransaction();
            agm_ft.replace(R.id.frag_containor, fragment2,
                    "agm_frag");
            agm_ft.addToBackStack(null);
            agm_ft.commit();

并将其恢复到下一个片段:

    Bundle getData = getArguments();
    title = getData.getString("title");

答案 1 :(得分:0)

1)创建Interface

public interface TitleChangeListener {
    public void onUpdateTitle(String title);
}

2)在Fragment 2

创建public方法

public void setTitle(String title){
    //Do Somthing
   }

3)让Activity实施Interface TitleChangeListener并覆盖onUpdateTitle

 public void onUpdateTitle(String title){
  fragment2.setTitle(title);
 }

4)在按钮onClickListner中,第一个Fragment

   TitleChangeListener listener=(TitleChangeListener)getActivity();
   listener.onUpdateTitle("Lady Gaga");

答案 2 :(得分:0)

要从一个片段到另一个片段获取字符串,您必须使用bundle并将它们设置为如下参数:

//on button click

String title = "Lady Gaga";

        Fragment fr = new Final_Categories_Fragment();
        Bundle b = new Bundle();

        b.putString("title", title);
        fragmentManager.beginTransaction()

                .add(R.id.list_frame, fr, "last").commit();
        fr.setArguments(b);

//Now on another fragment you have to get this argument 
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.sub_child_category_listview,
                container, false);
        ...

    String  title = getArguments().getString("title");
    ...
        return rootView;
    }