編輯:關於 Android 程式設計
Fragment 是 Android 3.0 之後引入的組件,目的是讓界面邏輯能夠復用到不同尺寸的屏幕上。實際開發中,Fragment 的用法大致可以歸成兩類:一種是在布局文件裡靜態聲明,一種是在代碼中動態添加。下面分別演示。
在一個水平的 LinearLayout 中放兩個豎向容器,左邊放按鈕,右邊留空用來承載 Fragment。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linerlayout1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#CCCCCC"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="顯示窗口" />
</LinearLayout>
<LinearLayout
android:id="@+id/linerlayout2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="#CCFFDD"
android:orientation="vertical" />
</LinearLayout>
這個布局沒有特殊要求,放什麼控件取決於業務。示例裡放了一個 RatingBar 和一個 Button。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點我試試" />
</LinearLayout>
繼承 Fragment 類,重點是重寫 onCreateView:在這裡 inflate 布局並完成控件初始化。
public class MyFragment extends Fragment {
public MyFragment() { }
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// R.layout.right 就是 Fragment 要展示的界面
View view = inflater.inflate(R.layout.right, null);
Button button = (Button) view.findViewById(R.id.button11);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "hello world!", Toast.LENGTH_LONG).show();
}
});
return view;
}
@Override
public void onPause() {
super.onPause();
}
}
注意 inflate 的第三個參數傳 null,因為 Fragment 會自己管理自己的視圖層級;同時 Toast 要用 getActivity() 而不是 getApplicationContext() 獲取 Context。
public class MainActivity extends Activity {
private Button button;
private FragmentManager fragmentManager; // 用於管理 Fragment
private FragmentTransaction fragmentTransaction; // 事務
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
fragmentManager = getFragmentManager();
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
// 第一個參數:放到哪個容器;第二個參數:要放入的 Fragment
fragmentTransaction.add(R.id.linerlayout2, myFragment);
fragmentTransaction.commit();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
效果是:點擊左側灰色區域的按鈕,右側出現 Fragment 的布局。


項目結構與上面基本一致,區別在於直接在布局裡寫 fragment 標簽:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.tablet_fragment_fragementmanager.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp" />
</RelativeLayout>
此時 MyFragment 只負責找到自己的布局即可,不做業務處理:
public class MyFragment extends Fragment {
public MyFragment() { }
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/* 只需返回布局文件 */
return inflater.inflate(R.layout.text, null);
}
@Override
public void onResume() {
super.onResume();
}
}
業務邏輯則全部放在 Activity 裡。由於 Fragment 已經寫死在布局中,不需要 beginTransaction,直接用 FragmentManager 按 ID 找到它就行:
/*
* 布局文件中拖入 fragment 後,用下面的方法找到特定的 fragment,
* 不需要使用 beginTransaction
*/
public class MainActivity extends Activity {
private MyFragment fragment;
private FragmentManager fragmentManager;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
// 使用 ID 作為唯一標識符查找 Fragment
fragment = (MyFragment) fragmentManager.findFragmentById(R.id.fragment1);
// 也可以按 tag 查找:
// fragment = (MyFragment) fragmentManager.findFragmentByTag("fragment1");
button = (Button) fragment.getView().findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "hello world!", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
靜態聲明(XML 中的 fragment 標簽)寫法簡單,但缺點很致命:一旦加入布局就無法在運行時替換或移除,也不方便接入返回棧。因此它只適合那些從頭到尾固定不變的界面塊。
動態添加(FragmentTransaction)靈活得多,可以配合 addToBackStack() 實現返回鍵逐層回退,也能隨時 replace、remove,是實際項目中的主流做法。官方後來推薦的 FragmentContainerView likewise 走的是動態路線。
一句話結論:學習階段兩種都該動手寫一遍,寫業務時預設選動態添加。
Android 火車票餘票查詢 App 實作分享
做了一個可以在手机上查詢動車與高鐵餘票的小工具,介面簡潔,操作直覺:輸入出發站與目的地、選擇日期,按下查詢就會列出當日各班次的餘票與時刻資訊。 功能概覽 車站選擇:支
Android 為 Button 綁定點擊事件的五種寫法與取捨
一、開場 這篇整理 Android 裡替 Button 綁定事件的五種常見寫法,並順便談談各自的優缺。 二、五種實作 第一種:直接在 XML 上綁定 步驟一,在 Butt
Android 靜態代碼檢查利器 Lint 的三種用法
基於 Gradle 的 Lint 檢查 在 gradle 中自帶了一個 lint 任務,可以直接執行靜態代碼檢查,但前提是你要在 build.gradle 中配置好 li
Android 裝置管理 API 實戰指南:企業如何有效管控員工手機
行動裝置走進辦公室之後,IT 管理者最在意的往往不是功能多不多,而是「這台裝置合不合規、資料安不安全」。Android 從 2.2 版本起提供了 Device Admin