Android-fragment簡介-fragment的簡單使用
阿新 • • 發佈:2018-12-26
1.fragment簡介
在Android3.0版本之前Google還沒有推出fragment,在Android3.0版本之後Google推出了fragment,由於Android3.0版本是過渡期版本,fragment真正大量使用是在Android4.0版本之後,已經有了Activity為什麼Google還有設計出fragment呢,是因為之前的Android版本一直是為手機考慮,後來慢慢的就決定要多裝置發展(例如:平板)所以有了fragment的出現
fragment是一個特殊的控制元件,fragment是有生命週期的控制元件,fragment必須在Activity之上執行(意思就是:fragment是被Activity定義和控制的)可以對 fragment 新增、移除、管理 等操作
Activity / Fragment開發過程中的比較:
可以理解為:Fragment的出現可以分離Activity程式碼
2.案例:簡單的 Fragment Demo
MyTestFragmentActivity
package liudeli.activity.fragment; import android.app.Activity; import android.os.Bundle; import liudeli.activity.R; public class MyTestFragmentActivity extendsActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_fragment); } }
MyTestFragmentActivity 的 佈局檔案
<?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- android:id="@+id/fragment" 必須要指定好ID,否則執行會報錯 class="liudeli.activity.fragment.MyFragment" 必須要指定class,否則無效果 --> <fragment android:id="@+id/fragment" class="liudeli.activity.fragment.MyFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
佈局 <fragment class 引用的 MyFragment
package liudeli.activity.fragment; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); TextView textView = new TextView(getActivity()); // 不能使用this,因為Fragment父類不是Context textView.setText("我是MyFragment"); /* 也可以是使用佈局載入器載入 View view = inflater.inflate(R.layout.xxx, null); view.findViewById(R.id.xxx); view.findViewById(R.id.xxx); ..... */ return textView; } }
效果: