Fragment 的静态方式和动态方式以及动态方式中fragment之间通过activity传递 数据(接口回调 ):

本文介绍了Android中Fragment的静态和动态加载方式,并详细阐述了如何在动态Fragment间通过接口回调进行数据传递。通过示例代码展示了在XML布局中声明Fragment与在代码中创建Fragment的区别,以及在Fragment中定义接口并在Activity中实现以完成数据交互的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

静态fragment的xml布局写法:
<RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/fragment_left_newstitle " 以便于在代码中操作该碎片
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.qf.fragment.LeftFragment" /> 自定义的Fragment 子类的全限定名 (包名加类名), 在该类中的onCre
ateView方法中,指定使用哪一个碎片的布局文件
</RelativeLayout>
-----------------------------------------------------
静态代码实例:
xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools= "http://schemas.android.com/tools"
    android:layout_width= "match_parent"
    android:layout_height= "match_parent"
    android:paddingBottom= "@dimen/activity_vertical_margin"
    android:paddingLeft= "@dimen/activity_horizontal_margin"
    android:paddingRight= "@dimen/activity_horizontal_margin"
    android:paddingTop= "@dimen/activity_vertical_margin"
    tools:context= ".MainActivity" >

    <fragment
        android:id="@+id/fragmentId"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.mrl.fragment.StaticFragment"
        />

</RelativeLayout>

主界面代码:
public class MainActivity extends Activity {
        private FragmentManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout. activity_main);
    }
}

Fragment的类中代码:
public class StaticFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
              // TODO Auto-generated method stub
             View view = inflater.inflate(R.layout. fragment_layout, null );
             
             TextView textView = (TextView) view.findViewById(R.id. textViewId);
             textView.setText( "我是fragment中的数据" );
              return view;
       }
}

总结:静态fragment中不能通过动态方式的方法来传递数据如下:
FragmentManager manager;
FragmentTransaction trans1 = manager.beginTransaction();
Fragment1 f1 = new Fragment1();
trans1.replace(R.id. frameLayoutId, f1);
trans1.addToBackStack( null);
trans1.commit();
静态布局我认为只是适合数据的展示,如果要 进行数据的传递用动态fragment更好些。具体的写法就是在布局中定义一个fragment,必须有id,和name(包名+类名)属性,主界面中什么也不用写,然后写个fragment类就行。
------------------------------
动态Fragment之间的数据传递:
2、 Fragment接口回调的步骤:(五步曲)
在Fragment 文件中定义接口:MyListener(名字随便) ,定义抽象方法 passValue(String info);
在Fragment 文件中定义属性:private MyListener mylistener;
在Fragment 文件中的onAttach ()方法中执行: mylistener = (MyListener) getActivity() ;
在Fragment 文件中,给某个控件增加监听器 (注意不能用onClick 属性指定),在监听器中执行: mylistener.passValue (需要
传递的数据 );
让MainActivity 实现MyListener ,重写passValue(String info) 方法。参数就是Fragment 传递给Activity的数据信息,在该方法中执
行希望的逻辑操作。

动态fragment的案例:(这个例子的作用是fragment1通过Activity向fragment2传递数据。)
xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools= "http://schemas.android.com/tools"
    android:layout_width= "match_parent"
    android:layout_height= "match_parent"
    android:orientation= "vertical"
    tools:context= ".MainActivity" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是主界面的textView" />
    <!-- 占位的布局 -->
   <FrameLayout
        android:id="@+id/frameLayoutId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 

</LinearLayout>

主界面的代码:
/*
 * fragment 之间传递数据;
 */
public class MainActivity extends Activity implements MyInter {

        private FragmentManager manager ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout. activity_main);
        manager = getFragmentManager();
        initFragment();
    }

    //初始化fragment
        private void initFragment() {
             FragmentTransaction trans1 = manager.beginTransaction();
             Fragment1 f1 = new Fragment1();
             trans1.replace(R.id. frameLayoutId, f1);
             trans1.addToBackStack( null);
             trans1.commit();
       }

        //接口回调的方法,在这个方法中接收数据并且传递给另一个Fragment2
        @Override
        public void passValue(String info) {
             
             FragmentTransaction trans = manager.beginTransaction(); //这个变量只能使用一次
             Fragment2 fm2 = new Fragment2();
             Bundle bundle = new Bundle();
             bundle.putString( "msg", info);
             fm2.setArguments(bundle);
             trans.add(R.id. frameLayoutId, fm2);
             trans.addToBackStack( null);
             trans.commit();
             
             Toast. makeText(this, info, 0).show();
       }
}

Fragment1类的代码:
public class Fragment1 extends Fragment {

        private MyInter  myInter ;
        public interface MyInter{
              public void passValue(String info);
       }
        @Override
        public void onAttach(Activity activity) {
              super.onAttach(activity);
              if (getActivity() instanceof MyInter) {//如果宿主Activity实现了该接口
                     myInter = (MyInter) getActivity(); //就将mylistener 指向该Activity
             }
       }

        private TextView textView ;
        private Button btn ;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
              // TODO Auto-generated method stub
             View view = inflater.inflate(R.layout. f1_fragment_layout, null );
              textView = (TextView) view.findViewById(R.id. text_detail);
              btn = (Button) view.findViewById(R.id. btnId);
              btn.setOnClickListener( new OnClickListener() {
                     @Override
                     public void onClick(View v) {
                            myInter.passValue( "我是fragment1中的信息" );
                    }

             });
              textView.setText( "你好");
              return view;
       }
}

Fragment2的代码实例:
public class Fragment2 extends Fragment {
       
        private TextView textView ;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              final View view = inflater.inflate(R.layout.f2_ragment_layout, null);
              textView = (TextView) view.findViewById(R.id. text_detail1);
             Bundle bundle = getArguments();
             String str = bundle.getString( "msg");
              textView.setText(str);
              return view;
       }

}
---------------------------------------
动态爱fragment中,fragment也可以通过Intent直接向Activity(也可以是本fragment的宿主activity)传递数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值