Android中的Fragment
文章目錄
- 1 Fragment簡介
- 1.1 設(shè)計(jì)思想
- 1.2 Fragment和Activity的區(qū)別
- 2 Fragment的生命周期
- 3 Fragment的靜態(tài)加載和動(dòng)態(tài)加載
- 3.1 Fragment的靜態(tài)加載
- 3.2 Fragment的動(dòng)態(tài)加載
- 3.3 Fragment使用示例
- 4 Activity和Fragment之間的相互傳值
- 4.1 Activity向Fragment傳值
- 4.1.1 通過Bundle傳值
- 4.1.2 通過對象傳值
- 4.2 Fragment向Activity傳值
1 Fragment簡介
1.1 設(shè)計(jì)思想
Fragment設(shè)計(jì)就是用來在平板上獲得更好的體驗(yàn),具體應(yīng)用場景直接看下圖即可:
1.2 Fragment和Activity的區(qū)別
Fragment和Activity的區(qū)別:
2 Fragment的生命周期
我們可以先來看下Fragment的生命周期:
下面來看下和Activity之間的關(guān)聯(lián):
下面看下當(dāng)一個(gè)Activity包含一格Fragment時(shí),生命周期的情況:
創(chuàng)建時(shí):
當(dāng)點(diǎn)擊返回按鍵時(shí):
3 Fragment的靜態(tài)加載和動(dòng)態(tài)加載
3.1 Fragment的靜態(tài)加載
靜態(tài)加載通過xml文件進(jìn)行設(shè)置即可,比較簡單:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><!--靜態(tài)加載通過android:name屬性指定Fragment的路徑--><fragmentandroid:id="@+id/fragment1"android:layout_width="200dp"android:layout_height="200dp"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent"android:name="com.example.fragmentdemo.Fragment1"/></androidx.constraintlayout.widget.ConstraintLayout>3.2 Fragment的動(dòng)態(tài)加載
先看下如何動(dòng)態(tài)加載Fragment:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i("TAG","Activity--onCreate");//FragmentManager FragmentTransaction//1.獲取Fragment管理器FragmentManager manager = getSupportFragmentManager();//2.獲取Fragment事務(wù)(/開啟事務(wù))FragmentTransaction transaction = manager.beginTransaction();//3.動(dòng)態(tài)添加Fragment//參數(shù)1:容器id//參數(shù)2:Fragment對象final Fragment f2 = new Fragment2();transaction.add(R.id.container,f2);//4.提交事務(wù)transaction.commit();}我們還可以動(dòng)態(tài)的更改Fragment中的內(nèi)容:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i("TAG","Activity--onCreate");//FragmentManager FragmentTransaction//1.獲取Fragment管理器FragmentManager manager = getSupportFragmentManager();//2.獲取Fragment事務(wù)(/開啟事務(wù))FragmentTransaction transaction = manager.beginTransaction();//3.動(dòng)態(tài)添加Fragment//參數(shù)1:容器id//參數(shù)2:Fragment對象final Fragment f2 = new Fragment2();transaction.add(R.id.container,f2);//4.提交事務(wù)transaction.commit();findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//1.獲取Fragment管理器FragmentManager manager = getSupportFragmentManager();//2.獲取Fragment對象Fragment f1 = manager.findFragmentById(R.id.fragment1); // 靜態(tài)//3.獲取Fragment對象的視圖View v1 = f1.getView();//4.再視圖里找到指定的控件TextView txt1 = v1.findViewById(R.id.txt1);//5.修改控件內(nèi)容txt1.setText("這是動(dòng)態(tài)生成的內(nèi)容");View v2 = f2.getView();TextView txt2 = v2.findViewById(R.id.txt2);txt2.setText("這個(gè)Fragment2的動(dòng)態(tài)內(nèi)容");}});}其實(shí)我們還可以在通過Fragment繼續(xù)添加Fragment:
public class Fragment2 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentView v = inflater.inflate(R.layout.fragment_fragment2, container, false);v.findViewById(R.id.txt2).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {FragmentTransaction transaction = getFragmentManager().beginTransaction();transaction.add(R.id.container , new Fragment3()); // transaction.remove(Fragment2.this);transaction.commit();}});return v;}}3.3 Fragment使用示例
我們通過Fragment實(shí)現(xiàn)如下導(dǎo)航實(shí)例:
注意這里需要使用選擇器,選擇器通常放在drawable文件夾中。
如下為設(shè)置圖標(biāo)的xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@mipmap/list_selected" android:state_checked="true"/><item android:drawable="@mipmap/list_normal"/> </selector>如下為設(shè)置文字顏色的xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:color="#ffffff" android:state_checked="true"/><item android:color="#515151"/> </selector>如下為設(shè)置背景的xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_checked="true"><shape><solid android:color="#FFC4C4C4"/></shape></item><item><shape><solid android:color="@android:color/transparent"/></shape></item> </selector>另外,如果很多控件都具有相同的屬性那么我們可以把共同的屬性抽取出來放到style中,看如下style:
<resources><!-- Base application theme. --><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"><!-- Customize your theme here. --><item name="colorPrimary">@color/colorPrimary</item><item name="colorPrimaryDark">@color/colorPrimaryDark</item><item name="colorAccent">@color/colorAccent</item></style><style name="tab_menu_item"><item name="android:layout_width">0dp</item><item name="android:layout_height">58dp</item><item name="android:layout_weight">1</item><item name="android:background">@drawable/tab_menu_bg</item><item name="android:textColor">@drawable/tab_menu_text</item><item name="android:textSize">18sp</item><item name="android:button">@null</item><item name="android:gravity">center</item><item name="android:paddingTop">3dp</item><item name="android:onClick">myclick</item></style> </resources>如下為Activity的xml文件:
<?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:layout_width="match_parent"android:layout_height="match_parent"tools:context=".TabFragmentActivity"android:orientation="vertical"><!--加載Framgent的容器--><FrameLayoutandroid:id="@+id/container"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"></FrameLayout><Viewandroid:layout_width="match_parent"android:layout_height="1dp"android:background="#515151"/><RadioGroupandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="#ffffff"android:orientation="horizontal"><RadioButtonandroid:id="@+id/rb_index"android:text="首頁"android:drawableTop="@drawable/tab_menu_index"style="@style/tab_menu_item"/><RadioButtonandroid:id="@+id/rb_rb_channel"android:text="分類"android:drawableTop="@drawable/tab_menu_channel"style="@style/tab_menu_item"/><RadioButtonandroid:id="@+id/rb_list"android:text="我的學(xué)習(xí)"android:drawableTop="@drawable/tab_menu_list"style="@style/tab_menu_item"/><RadioButtonandroid:id="@+id/rb_me"android:text="我"android:drawableTop="@drawable/tab_menu_me"style="@style/tab_menu_item"/><!--selector--></RadioGroup> </LinearLayout>java代碼如下:
package com.example.fragmentdemo;import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction;import android.os.Bundle; import android.util.Log; import android.view.View;public class TabFragmentActivity extends AppCompatActivity implements Fragment3.MyListener {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tab_fragment);FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();transaction.add(R.id.container,new IndexFragment());transaction.commit();}public void myclick(View view){FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();switch (view.getId()){case R.id.rb_index:transaction.replace(R.id.container,new IndexFragment());break;case R.id.rb_rb_channel:transaction.replace(R.id.container,new Fragment1());break;case R.id.rb_list:transaction.replace(R.id.container,new Fragment2());break;case R.id.rb_me:transaction.replace(R.id.container,new Fragment3());break;}transaction.commit();} }4 Activity和Fragment之間的相互傳值
4.1 Activity向Fragment傳值
4.1.1 通過Bundle傳值
傳值:
//setArguments //1.實(shí)例化Fragment Fragment f1 = new Fragment1(); //2.實(shí)例化一個(gè)Bundle對象 Bundle bundle = new Bundle(); //3.存入數(shù)據(jù)到Bundle對象中 bundle.putString("msg1","這是由Activity發(fā)往Fragment的數(shù)據(jù)"); //4.調(diào)用Fragment的setArguments方法,傳入Bundle對象 f1.setArguments(bundle); //5.添加/替換顯示的Fragment transaction.replace(R.id.container,f1);取出值:
//Fragment創(chuàng)建視圖@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentLog.e("TAG","onCreateView--Fragment視圖創(chuàng)建好了");View v = inflater.inflate(R.layout.fragment_fragment1, container, false);Bundle b = getArguments();String msg1 = b.getString("msg1");((TextView)v.findViewById(R.id.txt1)).setText(msg1);return v;}4.1.2 通過對象傳值
我們在Activity中拿到Fragment的對象,也可以在Fragment中拿到Activity的對象。所以可以通過私有方法傳值。
比如在Activity中存在如下方法:
public String sendMsg(){return "這是通過一個(gè)普通方法傳遞過去的消息"; }如下為Fragment中取出數(shù)值:
@Override public void onAttach(Context context) {super.onAttach(context);String msg = ((TabFragmentActivity)context).sendMsg();Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();Log.e("TAG","onAttach--Fragment與Activity關(guān)聯(lián)"); }4.2 Fragment向Activity傳值
Fragment像Activity傳值(接口回調(diào)):
先看下Fragment的代碼:
package com.example.fragmentdemo;import android.content.Context; import android.net.Uri; import android.os.Bundle;import androidx.fragment.app.Fragment;import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;public class Fragment3 extends Fragment {private String value;public String getValue() {return value;}public void setValue(String value) {this.value = value;}//Fragment像Activity傳值(接口回調(diào))//1.定義一個(gè)接口,在該接口中聲明一個(gè)用于傳遞數(shù)據(jù)的方法//2.讓Activity實(shí)現(xiàn)該接口,然后重寫回調(diào)方法,獲取傳入的值,然后做處理//3.在自定義Fragment中,聲明一個(gè)回調(diào)接口的引用//4.在onAttach中法中,為第三步的引用賦值//5.用引用調(diào)用傳遞數(shù)據(jù)的方法@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentreturn inflater.inflate(R.layout.fragment_fragment3, container, false);}private MyListener ml;@Overridepublic void onAttach(Context context) {super.onAttach(context);ml = (MyListener) getActivity();ml.sendMsg("消息");}public interface MyListener{public void sendMsg(String msg);} }再看下Activity的值:
package com.example.fragmentdemo;import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction;import android.os.Bundle; import android.util.Log; import android.view.View;public class TabFragmentActivity extends AppCompatActivity implements Fragment3.MyListener {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tab_fragment);FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();transaction.add(R.id.container,new IndexFragment());transaction.commit();}public void myclick(View view){FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();switch (view.getId()){case R.id.rb_index:transaction.replace(R.id.container,new IndexFragment());break;case R.id.rb_rb_channel://setArguments//1.實(shí)例化FragmentFragment f1 = new Fragment1();//2.實(shí)例化一個(gè)Bundle對象Bundle bundle = new Bundle();//3.存入數(shù)據(jù)到Bundle對象中bundle.putString("msg1","這是由Activity發(fā)往Fragment的數(shù)據(jù)");//4.調(diào)用Fragment的setArguments方法,傳入Bundle對象f1.setArguments(bundle);//5.添加/替換顯示的Fragmenttransaction.replace(R.id.container,f1);break;case R.id.rb_list:transaction.replace(R.id.container,new Fragment2());break;case R.id.rb_me:transaction.replace(R.id.container,new Fragment3());break;}transaction.commit();}public String sendMsg(){return "這是通過一個(gè)普通方法傳遞過去的消息";}@Overridepublic void sendMsg(String msg) {Log.e("TAG","Fragment傳回的數(shù)據(jù):"+msg);} }總結(jié)
以上是生活随笔為你收集整理的Android中的Fragment的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电阻应用电路之指示灯电路的设计
- 下一篇: 电阻应用电路之上下拉电阻