一、動態添加碎片
<?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:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="20sp" android:text="This is another right franment" /> ? </LinearLayout>
?
?我們先來修改一個布局的頁面,然后再將這個頁面添加到主頁面中去,如下XML
? <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" > ? <fragment android:id="@+id/left_fragment" android:name="com.example.fragmenttest.LeftFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <FrameLayout android:id="@+id/right_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <fragment android:id="@+id/right_fragment" android:name="com.example.fragmenttest.RightFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout> ?
我們制作好布局之后,然后開始編輯主活動
package com.example.fragmenttest; ? import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; ? public class MainActivity extends Activity implements OnClickListener{ ? @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(this); } ? @Override public void onClick(View v) { switch(v.getId()) { case R.id.button: AnotherRightFragment fragment = new AnotherRightFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.right_layout,fragment); transaction.commit(); break; default: break; } } }
?
?總結:(1)?創建待添加的碎片實體;?(2)獲取到FragmentManager,在活動中可以直接呼叫getFragmentManager()方法得到;(3)開啟一個事務,通過呼叫beginTransaction()方法進行開啟;(4)向容器中加入碎片,一般使用replace()方法實作,需要傳入容器的id和待添加的碎片實體?;(5)提交事務,呼叫?commit()方法完成,
二、原始碼:
1.專案地址
https://github.com/ruigege66/Android/tree/master/UIBestPractice
2.CSDN:https://blog.csdn.net/weixin_44630050
3.博客園:https://www.cnblogs.com/ruigege0000/
4.歡迎關注微信公眾號:傅里葉變換,個人公眾號,僅用于學習交流,后臺回復”禮包“,獲取大資料學習資料

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/7459.html
標籤:Android
上一篇:Ahjesus - Android Studio 最新版集成騰訊X5內核 TBS 必定成功
下一篇:Android 視圖影片
