美文网首页
fragment向fragment传值

fragment向fragment传值

作者: 小毕_先生 | 来源:发表于2018-01-11 19:16 被阅读0次

一,首页布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="laobi.com
.viewpagedemo.MainActivity">

  <fragment
  android:id="@+id/fragment_left"
  android:layout_width="0dp"
  android:layout_weight="1"
  android:layout_height="match_parent"/>

<fragment
  android:id="@+id/fragment_right"
  android:layout_width="0dp"
  android:layout_weight="1"
  android:layout_height="match_parent"/>

</LinearLayout>

二,实现方式;

  • 1,方式一:先调用getFragmentManager()对象,然后调用findFragmentById()方法获得目标fragment,将数据传递到目标fragment
    Fragment fragment_left = getFragmentManager().findFragmentById(R.id.fragment_left);
    fragment_left.setTextView(et_frafment.getText().toString().trim())//setTextView()是目标fragment自己定义的方法

  • 2,方式二: 先调用getFragmentManager()对象,然后调用findFragmentById()方法获得目标fragment,再调用getView()获得目标fragment的view对象,最后调用view的findViewById()获得目标控件
    TextView tv_fragment= (TextView)getFragmentManager()
    .findFragmentById(R.id.fragment_left).getView().findViewById(R.id.tv_fragment);

  • 3,方式三:先调用getActivity()获取所在的activity对象后,然后通过findViewById()找到目标控件(该目标fragment在activity中,所以可以通过activity进行findViewById)
    TextView tv_fragment = (TextView)getActivity().findViewById(R.id.tv_fragment);
    tv_fragment.setText(et_frafment.getText().toString().trim());

相关文章

网友评论

      本文标题:fragment向fragment传值

      本文链接:https://www.haomeiwen.com/subject/arnznxtx.html