Android中碎片的使用


Fragment的使用

其實碎片很簡單,但是網上胡亂充數的博文太多了,以至於我們有時候覺得比較亂,今天就來簡單講解一下碎片的使用.
碎片的使用分為兩種,靜態添加碎片和動態添加碎片,我們就先來看一下靜態添加碎片如何實現.

靜態添加碎片

首先,先建兩個Layout文件,這就是碎片的布局文件,大家可能也發現了,Android Studio里面可以直接快速建立碎片,就像Activity一樣,但是這樣會生成很多沒用的代碼,所以我們還是選擇自己創建碎片布局.

兩個布局都很簡單,里面只有一個居中顯示的TextView,下面貼一下代碼.

第一個布局文件:fragment_first.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:background="@android:color/holo_blue_light"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="This is the first fragment!"/>
</LinearLayout>

第二個布局文件fragment_second.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:background="@android:color/holo_green_light"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="This is the second fragment!"/>
</LinearLayout>

現在布局文件建完了,我們該建立他們對應的Fragment了,也就是后台代碼了。新建兩個類,分別叫FirstFragmentSecondFragment,都繼承於Fragment,需要注意一點,我們教程里面所使用的Fragment全都是android.support.v4.app.Fragment這個包下的,這樣更有利於程序的兼容性.

貼一下兩個類的代碼,也很簡單,只是重寫了onCreateView方法來加載不同的布局文件.

public class FirstFragment extends Fragment {
    private View view;//得到碎片對應的布局文件,方便后續使用

    //記住一定要重寫onCreateView方法
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_first, container, false);//得到對應的布局文件
        return view;
    }
}
public class SecondFragment extends Fragment {
    private View view;//得到碎片對應的布局文件,方便后續使用

    //記住一定要重寫onCreateView方法
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_second, container, false);//得到對應的布局文件
        return view;
    }
}

好,基本的工作我們做完了,現在我們用兩個Activity展示如何靜態添加碎片動態添加碎片.

靜態添加控件的話,需要使用fragment控件,指定其名稱是你剛才創建的Fragment就可以,讓我們來看一下.

先貼一下第一個Activity的布局:

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="me.worldskills.android.testfragment.MainActivity">

    <fragment
        android:id="@+id/main_firstfragment"
        android:name="me.worldskills.android.testfragment.FirstFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></fragment>

    <fragment
        android:id="@+id/main_secondfragment"
        android:name="me.worldskills.android.testfragment.SecondFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></fragment>

    <Button
        android:id="@+id/main_btnGoNext"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="Go to next page"
        android:textAllCaps="false"/>
</LinearLayout>

其中那個按鈕是用來跳轉到下一個界面的,也就是動態添加碎片案例的Activity,在這里可以忽略.

這里我們看見了,兩個fragment分別指定nameFirstFragmentSecondFragment,也就是你剛才創建的兩個Fragment,一定要記得加上包名.對了,還有一個問題,就是這樣的話是沒有預覽的,如果想要預覽,需要在fragment標簽中加上一句代碼:

Tools:layout="@layout/布局文件名稱"

好了,靜態添加碎片就完成了,什么?就這么簡單,對啊...就這么簡單.

動態添加碎片

動態添加碎片我們就不需要用fragment控件了,而是需要用個FrameLayout控件,這是為什么呢,首先我們都知道FrameLayout中的控件,都是從左上角開始顯示,不用進行位置控制,動態添加碎片其實就是向容器里面動態添加碎片,而fragment控件只能用來靜態綁定一個碎片.

先貼一下第二個Activity的布局:

<?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:id="@+id/activity_second"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/second_btnLoadFirst"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load First!"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/second_btnLoadSecond"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Second!"
        android:textAllCaps="false"/>

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

上面的兩個按鈕用來加載不同的碎片,而下面的FrameLayout就是碎片顯示的容器.

廢話不多說,貼代碼:

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        //點擊第一個按鈕的時候加載第一個碎片
        findViewById(R.id.second_btnLoadFirst).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.second_fl, new FirstFragment());
                transaction.commit();
            }
        });

        //點擊第二個按鈕的時候加載第二個碎片
        findViewById(R.id.second_btnLoadSecond).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSupportFragmentManager().beginTransaction().replace(R.id.second_fl, new SecondFragment()).commit();//簡寫
            }
        });
    }
}

getSupportFragmentManager方法用來獲得一個碎片管理器對象(使用這個方法的時候注意是android.support.v4.app包下的哦),然后通過這個方法開始一個碎片事物對象,這個對象比較關鍵,可以用來動態添加碎片,調用它的replace方法,會把指定容器里面的其他控件全部清除掉,然后添加新的碎片進去.在這里就是先把R.id.second_f1里面的控件清空,然后添加傳入一個FirstFragment進去.

替換完之后一定要記得調用commit方法提交,要不然你的所有操作都不會生效,切記.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM