1. 程式人生 > >【Android】建立和使用fragment

【Android】建立和使用fragment

SDK版本問題

1.系統需要執行在3.0(API 11)以及以上的版本,使用FragmentActivity繼承普通的Activity即可

2.系統需要執行在3.0(API 11)以下的版本,需要下載支援包android-support-v4.jar,並且使用FragmentActivity必須繼承android.support.v4.app.FragmentActivity。

實際上API11普通的的Activity集成了FragmentActivity。下面以3.0以及以上的版本為例。

Fragment類圖

public class

Fragment

extends Object
implements ComponentCallbacks2 View.OnCreateContextMenuListener
java.lang.Object
   ↳ android.app.Fragment
Known Direct Subclasses BrowseFragment, DetailsFragment, DialogFragment, ErrorFragment, HeadersFragment, ListFragment, PreferenceFragment, RowsFragment, SearchFragment, VerticalGridFragment, WebViewFragment
Known Indirect Subclasses PlaybackOverlayFragment

我們不但可以直接繼承Fragment建立Fragment,也可以繼承其他Fragment基類。

建立Fragment

Fragment類Fragment1.java:

package com.zzj.ui;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment1, container, false);
	}
}
Fragment類Fragment2.java:
package com.zzj.ui;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment2, container, false);
	}
}
Fragment佈局檔案Fragment1.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="#FF00FF"
    android:orientation="vertical" >

	<TextView android:text="menu" android:layout_width="match_parent" android:layout_height="match_parent"/>
</LinearLayout>
Fragment佈局檔案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:background="#FFFF00"
    android:orientation="vertical" >

	<TextView android:text="content" android:layout_width="match_parent" android:layout_height="match_parent"/>
</LinearLayout>

使用Fragment

Fragment依賴於Activity而存在,所以要使用Fragment,就必須將Fragment新增到Activity中。有兩種方法新增:

1.在Activity佈局檔案中使用fragment元素新增。

2.在Activity中使用程式碼新增。

在佈局檔案中新增fragment

fragmentdemo_activity.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:baselineAligned="false"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/fragment1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.zzj.ui.fragmentdemo.Fragment1" />

    <fragment
        android:id="@+id/fragment2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        class="com.zzj.ui.fragmentdemo.Fragment2" />

</LinearLayout>

Activity類:

package com.zzj.ui.fragmentdemo;

import com.zzj.ui.R;

import android.app.Activity;
import android.os.Bundle;

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

效果圖:


在Activity類中使用程式碼新增

fragmentdemo_activity.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:baselineAligned="false"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/fragment1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" >
    </FrameLayout>

    <FrameLayout
        android:id="@+id/fragment2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" >
    </FrameLayout>

</LinearLayout>
Activity類:
package com.zzj.ui.fragmentdemo;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;

import com.zzj.ui.R;

public class FragmentDemoActivity extends Activity {
	private Fragment1 fragment1;
	private Fragment2 fragment2;

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

		FragmentTransaction transaction = getFragmentManager()
				.beginTransaction();
		fragment1 = (Fragment1) getFragmentManager().findFragmentByTag("f1");
		if (fragment1 == null) {
			fragment1 = new Fragment1();
			transaction.add(R.id.fragment1, fragment1, "f1");
		}
		fragment2 = (Fragment2) getFragmentManager().findFragmentByTag("f2");
		if (fragment2 == null) {
			fragment2 = new Fragment2();
			transaction.add(R.id.fragment2, fragment2, "f2");
		}
		transaction.commit();
	}
}

效果同上。

Activity以事務的方式對Fragment進行管理。




相關推薦

Android建立使用fragment

SDK版本問題 1.系統需要執行在3.0(API 11)以及以上的版本,使用Fragment的Activity繼承普通的Activity即可。 2.系統需要執行在3.0(API 11)以下的版本,需要下載支援包android-support-v4.jar,並且使用Fragm

ObjectARX--建立訪問圖形資料庫(DwgDatabase)

(1)使用ObjectARX建立新工程DwgDatabase,選擇MFC支援。 (2)註冊一個命令CreateDwg建立一個新的圖形檔案,並儲存在AutoCAD的安裝路徑中. 實現函式為: static void AAAMyGroupCreateDwg() {

AndroidstartServicebindService混合使用總結

先自定義一個service: public class MyService extends Service { private Service startService; private Service bindService; @Nullable

AndroidSDKAPI Level版本的對應關係

這裡記錄一下android的SDK和API版本號之間的對應關係,方便以後的檢視。 舉例 例如以下的 build.gradle 配置檔案指定了專案相容的最低android A

AndroidFragment真正意義上的onResumeonPause

    @Override     public void setUserVisibleHint(boolean isVisibleToUser) {         super.setUserVisibleHint(isVisibleToUser);         if (isVisibleToUser)

androiduses-permissionpermission具體解釋

.com 新的 -i weight bsp htm fin article 程序 1.<uses-permission>: 官方描寫敘述: If an application needs access to a feature prote

Android獲取控件的寬

height string -a @override parent popu tle post spa 有時候我們須要在Activity的時候獲取控件的寬和高來做一些操作,以下介紹三種獲取寬和高的方式: 1. onWindowFoc

Android從無到有:手把手一步步教你使用最簡單的Fragment(三)

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80585416 【本文適用讀者】         用程式碼建立並使用了 Fragment,新增 Fragment 之

Android從無到有:手把手一步步教你使用最簡單的Fragment(二)

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80579389 【本文適用讀者】         targetSdkVersion 版本大於等於 21,即 app 即將有可能

Android從無到有:手把手一步步教你使用最簡單的 Fragment(一)

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80515227 【本文適用讀者】         知道 Fragment 是什麼,不知

ROS建立PublisherSubscriber過程中遇到的問題解決方案

Tutorial連結:http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29   1. 寫好並儲存好了talker.cpp和listener.cpp卻無法建立 檢查~/catkin

ROS建立工作空間程式包

要使用ROS系統進行開發,首先需要在ROS下建立工作空間(workspace)和程式包(package)。 建立工作空間: $ mkdir -p ~/catkin_ws/src 執行上述命令即在使用者主目錄下建立了catkin_ws資料夾及其子資料夾src(-p表示建立目標路徑上的所

Android一、Progress進度條實現的三種方式:主執行緒實現,Service載入,動態建立

前言 更新版本,上傳資料到服務端,都是需要進度顯示的,Android進度顯示兩種方式 ProgressDialog 和 ProgressBar 新版本中ProgressDialog不被推薦使用,所以專案採用ProgressBar 分為三種實現方式: 1、MainAct

Androidadb抓取不同分類Log(kernel、radio、event、main)獲取ANR log

Log分類     Android日誌主要分為kernel、radio、event、main這四種log。 Kernel Log     kernel log屬於Linux核心的log ,可以通過讀取/proc/kmsg或者通過串列埠來抓取。     adb 抓取ke

Androidandroid中InvalidatepostInvalidate的區別

Android中實現view的更新有兩組方法,一組是invalidate,另一組是postInvalidate,其中前者是在UI執行緒自身中使用,而後者在非UI執行緒中使用。 Android提供了Invalidate方法實現介面重新整理,但是Invalidate不能直接線上程中呼叫,因為他是違背了單執行緒模型

Android專案中資料夾檔案的作用

Table of Contents 資料夾的作用  檔案的作用    資料夾的作用  No. 資料夾 描述 1 src 存放

android關於FragmentManager動態管理FragmentFragment生命週期的探究

Fragment是Android中的重要元件,在Android 3.0的時候新增進來。 關於Fragment的生命週期,我相信瞭解過的開發人員都應該把以下方法脫口而出:onAttach, onCreate, onCreateView, onViewCreated, on

AndroidRetrofit的使用(4)-Retrofit進行簡單的GETPOST訪問操作

1.GET方式提交資料 第一種方法: @GET("account/login.action") Call<JSONObject> login(@Query("<span styl

AndroidFragmentFragment生命週期

Fragment每個生命週期方法的意義、作用(注意紅色的不是生命週期方法):setUserVisibleHint():設定Fragment可見或者不可見時會呼叫此方法。在該方法裡面可以通過呼叫getUserVisibleHint()獲得Fragment的狀態是可見還是不可見的,如果可見則進行懶載入操作。onA

Android FragmentTabHost+Fragment實現多標籤頁

Android TabHost多標籤頁幾乎是所有APP中必備的控制元件,如通迅錄的【撥號、通話記錄、聯絡人】,微信的【聊天、聯絡人、發現】,如下圖 Android API13之後官方就不推薦使用TabActivity了,取而代之的是FragmentActivity+F