动态加载Fragment

用动态加载Fragment实现Fragment与Activity通信

处理Fragment事务
根据用户的交互情况,对Fragment进行添加,移除,替换,以及执行其他动作,提交给Activity的每一套变化被称作一个事务

//获取Fragment的管理者
FragmentManager fragmentManager=getFragmentManager();
//开启一个事务
FragmentTransaction beginTransaction=fragmentManager.beginTransaction();

每一个事务都是同时执行一套变化,可以在一个事务中设置你所有想执行的变化,包括add(),remove(),replace(),然后提交给Activity,必须调用commit()方法

如果允许用户通过按下BACK键返回到前一个Fragment状态,调用commit()之前可以加入addToBackStack()方法
Fragment与Activity之间的通信

  • Fragment可调用getActivity()方法获取它所在的Activity
  • Activity可调用FragmentManager的findFragmentById()或findFragmentByTag()方法获取Fragment

  • Activity—Fragment:在Activity中创建Bundle数据包,并调用Fragment的setArguemnts(Bundle bundle)方法,此时可在Fragment中通过getArguments(Bundle bundle)方法获得Activity传来的数据包并解析

  • Fragment—Activity:需要在Fragment中定义一个内部回调接口,再让包含该Fragment的Activity实现该回调接口,这样Fragment可调用该回调方法将数据传给Activity

布局文件main4.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/layout" >
   <EditText 
       android:id="@+id/editText"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="发送"
       android:id="@+id/send"/>
</LinearLayout>

fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="add"
        android:id="@+id/bt_1"/>
     <Button 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="rm"
        android:id="@+id/bt_2"/>
     <TextView 
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:id="@+id/tv"/>


</LinearLayout>

MyFragment4.java
- 初始化字符串(Fragment所要传递给Activity的信息)

    private String str="Thank you,Activity!";
  • 在Fragment中定义一个内部回调接口(Fragment—Activity)
public class MyFragment4 extends Fragment{
    //加载Fragment对应的布局

    public MyListener listener;
    public interface MyListener{
        public void Thank(String str);
    }
    @Override
    //当该Fragement被添加到Activity中会添加的方法
    public void onAttach(Activity activity) {
        //使得listener获取一个activity对象
        listener=(MyListener) activity;
        super.onAttach(activity);
    }
  • 将layout布局文件转换成view对象
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /*
         *参数1(resource):Fragment所需要加载的布局文件
         *参数2(root):加载layout的父组件viewGroup
         *参数3(attachToRoot):false,不返回父viewGroup(因为已经加载了父viewGroup)
         */
        View view=inflater.inflate(R.layout.fragment2, container, false);
        TextView tv=(TextView)view.findViewById(R.id.tv);//因为所布局的文件已经放在view里了,所以一定要加一个view前缀
  • 在Fragment中通过getArguments(Bundle bundle)方法获得Activity传来的数据包并解析(Activity—Fragment)
  • Fragment可调用getActivity()方法获取它所在的Activity
    String text=getArguments().get("name")+"";//获取所对应的数据包(Bundle类型),解析
        //通过getActivity()获得数组Activity的对象
        Toast.makeText(getActivity(),"已成功接收到"+text, Toast.LENGTH_SHORT).show(); 
        Toast.makeText(getActivity(),"已向Activity成功发送"+str, Toast.LENGTH_SHORT).show(); 
        listener.Thank(str);
        tv.setText(text);
        return view;

    }

MainActivity4.java

  • 实现Fragment(MyFragment4)中定义的接口MyListener(Fragment—Activity)
 public class MainActivity4 extends Activity implements MyListener

初始化main4.xml中的控件

    private EditText editText;
    private Button send;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main4);
        editText=(EditText) findViewById(R.id.editText);
        send=(Button) findViewById(R.id.send);

实现send按钮的OnClick方法

  • 在Activity中创建Bundle数据包,并调用Fragment的setArguemnts(Bundle bundle)方法(Activity—Fragment)
send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //发送文本信息给Fragment
                String text=editText.getText().toString();
                /*直接创建了MyFragment4类型的Fragment,所以不需
                 *要使用findFragmentById方法  
                 */                            
                MyFragment4 fragment4=new MyFragment4();
                //在Activity中创建Bundle数据包
                Bundle bundle=new Bundle();
                bundle.putString("name", text);
                //调用Fragement的setArguments(Bundle bundle)方法
                fragment4.setArguments(bundle);
                //获取Fragment的管理者
                FragmentManager fragmentManager=getFragmentManager();
                //开启一个事务
                FragmentTransaction beginTransaction=fragmentManager.beginTransaction();
                /*
                 * 参数1:需要把fragment2加载到哪个布局,就写入哪个布局的id
                 * 参数3:tag
                 */
                beginTransaction.add(R.id.layout,fragment4,"fragment4");
                beginTransaction.commit();//提交事务
                Toast.makeText(MainActivity4.this,"向Fragment发送数据"+text, Toast.LENGTH_SHORT).show();
            }
        });
    }
  • 实现所包含的Fragment中定义的接口中未实现的方法实现,这样Fragment可调用该回调方法将数据传给Activity
@Override
    public void Thank(String str) {
        Toast.makeText(MainActivity4.this, "已成功收到"+str+"客气了",Toast.LENGTH_SHORT).show();

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值