动态添加Fragment

在Fragment简单用法的基础上做修改

 

一.新建:another_right_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#0000ff">

 

    <TextView

        android:text="另一个raight fragment"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/textView3"

        android:layout_weight="1" />

</LinearLayout>

 

 

二.新建AnotherRightFragment类:

 

public class AnotherRightFragment extends Fragment {

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.another_right_fragment, container, false);

        return view;

    }

}

 

 

三.修改activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<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">

    <fragment

        android:layout_width="0dp"

        android:layout_height="match_parent"

        android:name="com.example.guo.fragment.LeftFragment"

        android:layout_weight="1"

        android:id="@+id/left_fragment" />

 

    <fragment

        android:layout_width="0dp"

        android:layout_height="match_parent"

        android:name="com.example.guo.fragment.RightFragment"

        android:layout_weight="1"

        android:id="@+id/right_fragment" />

</LinearLayout>

 

四.修改left_fragment.xml

给按钮增加android:onClick="myClick"

 

五.修改MainActivity,增加click方法,

     protected void myClick(View view){

        if( view.getId() == R.id.btn ){

            AnotherRightFragment anotherRightFragment = new AnotherRightFragment();

            FragmentManager fragmentManager = getFragmentManager();

            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.replace(R.id.right_fragment, anotherRightFragment);

            fragmentTransaction.addToBackStack(null); // 按下返回键,返回上一个Fragment;不加改行,则直接退出应用

            fragmentTransaction.commit();

        }

    }

 

 

 

可以看到,首先我们给左侧碎片中的按钮注册了一个点击事件,然后将动态添加碎片的

逻辑都放在了点击事件里进行。结合代码可以看出,动态添加碎片主要分为5 步。

1. 创建待添加的碎片实例。

2. 获取到FragmentManager,在活动中可以直接调用getFragmentManager()

方法得到。

3. 开启一个事务,通过调用beginTransaction()方法开启。

4. 向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id 和待添加的

碎片实例。

5. 提交事务,调用commit()方法来完成。

posted @ 2017-04-19 11:23  rorshach  阅读(240)  评论(0编辑  收藏  举报