溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Fragment如何在Android中使用

發(fā)布時間:2021-04-08 15:27:19 來源:億速云 閱讀:195 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)Fragment如何在Android中使用,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

Fragment初探

為了讓界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常類似于Activity,可以像Activity一樣包含布局。Fragment通常是嵌套在Activity中使用的,現(xiàn)在想象這種場景:有兩個Fragment,F(xiàn)ragment 1包含了一個ListView,每行顯示一本書的標(biāo)題。Fragment 2包含了TextView和ImageView,來顯示書的詳細(xì)內(nèi)容和圖片。

如果現(xiàn)在程序運行豎屏模式的平板或手機上,F(xiàn)ragment 1可能嵌入在一個Activity中,而Fragment 2可能嵌入在另一個Activity中,如下圖所示:

Fragment如何在Android中使用

而如果現(xiàn)在程序運行在橫屏模式的平板上,兩個Fragment就可以嵌入在同一個Activity中了,如下圖所示:

Fragment如何在Android中使用

由此可以看出,使用Fragment可以讓我們更加充分地利用平板的屏幕空間,下面我們一起來探究下如何使用Fragment。

首先需要注意,F(xiàn)ragment是在3.0版本引入的,如果你使用的是3.0之前的系統(tǒng),需要先導(dǎo)入android-support-v4的jar包才能使用Fragment功能。

新建一個項目叫做Fragments,然后在layout文件夾下新建一個名為fragment1.xml的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00" >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 1"
        android:textColor="#000000"
        android:textSize="25sp" />
 
</LinearLayout>

可以看到,這個布局文件非常簡單,只有一個LinearLayout,里面加入了一個TextView。我們?nèi)绶ㄅ谥圃傩陆ㄒ粋€fragment2.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff00" >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 2"
        android:textColor="#000000"
        android:textSize="25sp" />
 
</LinearLayout>

然后新建一個類Fragment1,這個類是繼承自Fragment的:

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

我們可以看到,這個類也非常簡單,主要就是加載了我們剛剛寫好的fragment1.xml布局文件并返回。同樣的方法,我們再寫好Fragment2 :

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

然后打開或新建activity_main.xml作為主Activity的布局文件,在里面加入兩個Fragment的引用,使用android:name前綴來引用具體的Fragment:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false" >
 
    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fragmentdemo.Fragment1"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1" />
 
    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragmentdemo.Fragment2"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1" />
 
</LinearLayout>

最后打開或新建MainActivity作為程序的主Activity,里面的代碼非常簡單,都是自動生成的:

public class MainActivity extends Activity {
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
 
}

現(xiàn)在我們來運行一次程序,就會看到,一個Activity很融洽地包含了兩個Fragment,這兩個Fragment平分了整個屏幕,效果圖如下:

Fragment如何在Android中使用

動態(tài)添加Fragment

你已經(jīng)學(xué)會了如何在XML中使用Fragment,但是這僅僅是Fragment最簡單的功能而已。Fragment真正的強大之處在于可以動態(tài)地添加到Activity當(dāng)中,因此這也是你必須要掌握的東西。當(dāng)你學(xué)會了在程序運行時向Activity添加Fragment,程序的界面就可以定制的更加多樣化。下面我們立刻來看看,如何動態(tài)添加Fragment。

還是在上一節(jié)代碼的基礎(chǔ)上修改,打開activity_main.xml,將其中對Fragment的引用都刪除,只保留最外層的LinearLayout,并給它添加一個id,因為我們要動態(tài)添加Fragment,不用在XML里添加了,刪除后代碼如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false" >
 
</LinearLayout>

然后打開MainActivity,修改其中的代碼如下所示:

public class MainActivity extends Activity {
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Display display = getWindowManager().getDefaultDisplay();
		if (display.getWidth() > display.getHeight()) {
			Fragment1 fragment1 = new Fragment1();
			getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
		} else {
			Fragment2 fragment2 = new Fragment2();
			getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
		}
	}
 
}

首先,我們要獲取屏幕的寬度和高度,然后進(jìn)行判斷,如果屏幕寬度大于高度就添加fragment1,如果高度大于寬度就添加fragment2。動態(tài)添加Fragment主要分為4步:

1.獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。

2.開啟一個事務(wù),通過調(diào)用beginTransaction方法開啟。

3.向容器內(nèi)加入Fragment,一般使用replace方法實現(xiàn),需要傳入容器的id和Fragment的實例。

4.提交事務(wù),調(diào)用commit方法提交。

現(xiàn)在運行一下程序,效果如下圖所示:

Fragment如何在Android中使用

如果你是在使用模擬器運行,按下ctrl + F11切換到豎屏模式。效果如下圖所示:

Fragment如何在Android中使用

Fragment的生命周期

和Activity一樣,F(xiàn)ragment也有自己的生命周期,理解Fragment的生命周期非常重要,我們通過代碼的方式來瞧一瞧Fragment的生命周期是什么樣的:

public class Fragment1 extends Fragment {
	public static final String TAG = "Fragment1";
 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView");
		return inflater.inflate(R.layout.fragment1, container, false);
	}
 
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		Log.d(TAG, "onAttach");
	}
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate");
	}
 
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.d(TAG, "onActivityCreated");
	}
 
	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, "onStart");
	}
 
	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
	}
 
	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPause");
	}
 
	@Override
	public void onStop() {
		super.onStop();
		Log.d(TAG, "onStop");
	}
 
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Log.d(TAG, "onDestroyView");
	}
 
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}
 
	@Override
	public void onDetach() {
		super.onDetach();
		Log.d(TAG, "onDetach");
	}
 
}

可以看到,上面的代碼在每個生命周期的方法里都打印了日志,然后我們來運行一下程序,可以看到打印日志如下:

Fragment如何在Android中使用

這時點擊一下home鍵,打印日志如下:

Fragment如何在Android中使用

如果你再重新進(jìn)入進(jìn)入程序,打印日志如下:

Fragment如何在Android中使用

然后點擊back鍵退出程序,打印日志如下:

Fragment如何在Android中使用

看到這里,我相信大多數(shù)朋友已經(jīng)非常明白了,因為這和Activity的生命周期太相似了。只是有幾個Activity中沒有的新方法,這里需要重點介紹一下:

  • onAttach方法:Fragment和Activity建立關(guān)聯(lián)的時候調(diào)用。

  • onCreateView方法:為Fragment加載布局時調(diào)用。

  • onActivityCreated方法:當(dāng)Activity中的onCreate方法執(zhí)行完后調(diào)用。

  • onDestroyView方法:Fragment中的布局被移除時調(diào)用。

  • onDetach方法:Fragment和Activity解除關(guān)聯(lián)的時候調(diào)用。

Fragment之間進(jìn)行通信

通常情況下,Activity都會包含多個Fragment,這時多個Fragment之間如何進(jìn)行通信就是個非常重要的問題了。我們通過一個例子來看一下,如何在一個Fragment中去訪問另一個Fragment的視圖。

還是在第一節(jié)代碼的基礎(chǔ)上修改,首先打開fragment2.xml,在這個布局里面添加一個按鈕:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ffff00" >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 2"
        android:textColor="#000000"
        android:textSize="25sp" />
    
    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get fragment1 text"
        />
 
</LinearLayout>

然后打開fragment1.xml,為TextView添加一個id:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00" >
 
    <TextView
        android:id="@+id/fragment1_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 1"
        android:textColor="#000000"
        android:textSize="25sp" />
 
</LinearLayout>

接著打開Fragment2.java,添加onActivityCreated方法,并處理按鈕的點擊事件:

public class Fragment2 extends Fragment {
 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment2, container, false);
	}
 
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Button button = (Button) getActivity().findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
				Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
			}
		});
	}
 
}

現(xiàn)在運行一下程序,并點擊一下fragment2上的按鈕,效果如下圖所示:

Fragment如何在Android中使用

以上就是Fragment如何在Android中使用,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI