Fragment碎片的使用

碎片是什么?
碎片(Fragment)是一种可以嵌入在活动当中的UI 片段,它能让程序更加合理和充分
地利用大屏幕的空间,因而在平板上应用的非常广泛。虽然碎片对你来说应该是个全新的概
念,但我相信你学习起来应该毫不费力,因为它和活动实在是太像了,同样都能包含布局,
同样都有自己的生命周期。你甚至可以将碎片理解成一个迷你型的活动,虽然这个迷你型的活动有可能和普通的活动是一样大的。

碎片的简单用法

我们新建一个布局文件叫left_fragment.xml

<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:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button"
/>
</LinearLayout>

这个布局非常简单,只放置了一个按钮,并让它水平居中显示。然后新建右侧碎片布局
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="#00ff00"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:text="This is right fragment"
/>
</LinearLayout>

可以看到,我们将这个布局的背景色设置成绿色,并放置了一个TextView 用于显示一
段文本。接着新建一个LeftFragment 类,继承自Fragment。注意,这里可能会有两个不同包下的Fragment 供你选择,建议使用android.app.Fragment,因为我们的程序是面向Android 4.0
以上系统的,另一个包下的Fragment 主要是用于兼容低版本的Android 系统。LeftFragment的代码如下所示:

public class LeftFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment, container, false);
return view;
}
}

这里仅仅是重写了Fragment 的onCreateView()方法,然后在这个方法中通过LayoutInflater
的inflate()方法将刚才定义的left_fragment 布局动态加载进来,整个方法简单明了。接着我们用同样的方法再新建一个RightFragment,代码如下所示:

public class RightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_fragment, container, false);
return view;
}
}

接下来修改activity_main.xml中的代码,如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>

以上是很简单的例子,实际开发是远远不够的。

动态添加碎片

动态添加碎片用的地方非常之多。

我们先创建四个Fragment

public class FramentOne extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View view=inflater.inflate(R.layout.framentone, container, false);
            return view;
        }
}

public class FramentTwo extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view=inflater.inflate(R.layout.framenttwo, container, false);
        return view;
    }
}
public class FramentThree extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view=inflater.inflate(R.layout.framentthree, container, false);
        return view;
    }
}
public class FramentFour extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view=inflater.inflate(R.layout.framentfour, container, false);
        return view;
    }
}

下面是main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF" >

    <FrameLayout
        android:id="@+id/framelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >


        <fragment
            android:id="@+id/mainone"
            android:name="com.caogenqing.android2016.FramentOne"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Btn1"
            android:textColor="#000000"
            android:textSize="16sp" >
        </TextView>

        <TextView
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Btn2"
            android:textColor="#000000"
            android:textSize="16sp" >
        </TextView>

        <TextView
            android:id="@+id/btn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Btn3"
            android:textColor="#000000"
            android:textSize="16sp" >
        </TextView>

        <TextView
            android:id="@+id/btn4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Btn4"
            android:textColor="#000000"
            android:textSize="16sp" >
        </TextView>
    </LinearLayout>

</RelativeLayout>

下面是MainActivity.java

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
//调用的都是v4的包。是为了兼容低版本建议用android.app下的包
public class FarmentActivity extends FragmentActivity implements
        OnClickListener {
    private TextView btnone, btntwo, btnthree, btnfour;

    @Override
    protected void onCreate(Bundle arg0) {
        // TODO Auto-generated method stub
        super.onCreate(arg0);
        setContentView(R.layout.framentmain);
        btnone = (TextView) findViewById(R.id.btn1);
        btntwo = (TextView) findViewById(R.id.btn2);
        btnthree = (TextView) findViewById(R.id.btn3);
        btnfour = (TextView) findViewById(R.id.btn4);
        btnone.setOnClickListener(this);
        btntwo.setOnClickListener(this);
        btnthree.setOnClickListener(this);
        btnfour.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn1:
            // 首先创建fragement对象
            FramentOne framentOne = new FramentOne();
            // 获取到FragmentManager,在活动中可以直接调用getFragmentManager()方法得到。

            FragmentManager manager = getSupportFragmentManager();
            Log.e("manager", "" + manager);
            // 开启一个事务,通过调用beginTransaction()方法开启。
            FragmentTransaction transaction = manager.beginTransaction();
            // 向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id 和待添加的碎
            // 片实例。
            transaction.replace(R.id.mainone, framentOne);
            // 提交
            transaction.commit();
            break;
        case R.id.btn2:
            FramentTwo framentTwo = new FramentTwo();
            FragmentManager manager2 = getSupportFragmentManager();
            FragmentTransaction transaction2 = manager2.beginTransaction();
            transaction2.replace(R.id.mainone, framentTwo);
            transaction2.commit();
            break;
        case R.id.btn3:
            FramentThree framentThree = new FramentThree();
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction3 = fragmentManager
                    .beginTransaction();
            transaction3.replace(R.id.mainone, framentThree);
            transaction3.commit();
            break;
        case R.id.btn4:
            FramentFour framentFour=new FramentFour();
            FragmentManager fragmentManager2=getSupportFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager2.beginTransaction();
            fragmentTransaction.replace(R.id.mainone, framentFour);
            fragmentTransaction.commit();
            break;
        default:
            break;
        }
    }
}

在碎片中模拟返回栈

尝试一下就会发现,通过点击按钮添加了一个碎片之后,这时按下Back 键程序就会直接退出。如果这里我们想模仿类似于返回栈的效果,按下Back 键可以回到上一个碎片,该如何实现呢?
其实很简单,FragmentTransaction 中提供了一个addToBackStack()方法,可以用于将一个事务添加到返回栈中

switch (v.getId()) {
        case R.id.btn1:
            // 首先创建fragement对象
            FramentOne framentOne = new FramentOne();
            // 获取到FragmentManager,在活动中可以直接调用getFragmentManager()方法得到。
            FragmentManager manager = getSupportFragmentManager();
            Log.e("manager", "" + manager);
            // 开启一个事务,通过调用beginTransaction()方法开启。
            FragmentTransaction transaction = manager.beginTransaction();
            // 向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id 和待添加的碎
            // 片实例。
            transaction.replace(R.id.mainone, framentOne);
            transaction.addToBackStack(null);
            // 提交
            transaction.commit();
            break;

这里我们在事务提交之前调用了FragmentTransaction 的addToBackStack()方法,它可以接收一个名字用于描述返回栈的状态,一般传入null 即可。现在重新运行程序,并点击按钮将AnotherRightFragment 添加到活动中,然后按下Back 键,你会发现程序并没有退出,而是回到了RightFragment 界面,再次按下Back 键程序才会退出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值