Android Fragment 的使用小結(jié)
Android 中 Fragment 的使用指南
Fragment 是 Android 應(yīng)用開發(fā)中的重要組件,它代表 Activity 中的一部分 UI 或行為,可以組合多個 Fragment 在一個 Activity 中構(gòu)建多窗格 UI,并在不同 Activity 中重復(fù)使用某個 Fragment。
基本概念
Fragment 具有自己的生命周期,但依賴于宿主 Activity 的生命周期。每個 Fragment 都有自己的布局和行為。
創(chuàng)建 Fragment
1. 定義 Fragment 類
public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 膨脹 fragment 的布局 return inflater.inflate(R.layout.fragment_my, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // 在這里初始化視圖和邏輯 } }
2. 創(chuàng)建 Fragment 的布局文件 (res/layout/fragment_my.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello Fragment!" /> </LinearLayout>
添加 Fragment 到 Activity
方式1: 在 XML 布局中添加 (靜態(tài)方式,不推薦)
<!-- activity_main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/myFragment" android:name="com.example.MyFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
方式2: 在代碼中動態(tài)添加 (推薦)
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 檢查是否已經(jīng)添加了Fragment(防止旋轉(zhuǎn)時重復(fù)添加) if (savedInstanceState == null) { // 創(chuàng)建Fragment實例 MyFragment fragment = new MyFragment(); // 開始Fragment事務(wù) getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, fragment) // 添加到容器 .commit(); } } }
對應(yīng)的 activity_main.xml 需要有一個容器:
<FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />
Fragment 事務(wù)
可以執(zhí)行添加、移除、替換等操作:
// 替換Fragment getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new AnotherFragment()) .addToBackStack(null) // 允許用戶按返回鍵返回上一個Fragment .commit();
Fragment 生命周期
Fragment 的生命周期方法:
- onAttach() - Fragment 與 Activity 關(guān)聯(lián)時調(diào)用
- onCreate() - Fragment 創(chuàng)建時調(diào)用
- onCreateView() - 創(chuàng)建 Fragment 的視圖層次結(jié)構(gòu)
- onActivityCreated() - Activity 的 onCreate() 完成后調(diào)用
- onStart() - Fragment 可見時調(diào)用
- onResume() - Fragment 可交互時調(diào)用
- onPause() - Fragment 不再可交互時調(diào)用
- onStop() - Fragment 不可見時調(diào)用
- onDestroyView() - Fragment 的視圖被移除時調(diào)用
- onDestroy() - Fragment 不再使用時調(diào)用
- onDetach() - Fragment 與 Activity 解除關(guān)聯(lián)時調(diào)用
Fragment 與 Activity 通信
1. Fragment 調(diào)用 Activity 方法
// 在Fragment中 if (getActivity() instanceof MyActivityInterface) { ((MyActivityInterface) getActivity()).doSomething(); } // Activity實現(xiàn)接口 public interface MyActivityInterface { void doSomething(); }
2. Activity 調(diào)用 Fragment 方法
MyFragment fragment = (MyFragment) getSupportFragmentManager() .findFragmentById(R.id.my_fragment); if (fragment != null) { fragment.doSomethingInFragment(); }
3. 使用 ViewModel 共享數(shù)據(jù) (推薦)
// 創(chuàng)建共享ViewModel public class SharedViewModel extends ViewModel { private final MutableLiveData<String> selected = new MutableLiveData<>(); public void select(String item) { selected.setValue(item); } public LiveData<String> getSelected() { return selected; } } // 在Activity或Fragment中獲取 SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); model.getSelected().observe(this, item -> { // 更新UI });
最佳實踐
- 使用
androidx.fragment.app
包中的 Fragment(支持庫版本) - 避免在 Fragment 中直接持有 Activity 的引用
- 使用接口進行 Fragment 與 Activity 的通信
- 考慮使用 ViewModel 和 LiveData 進行數(shù)據(jù)共享
- 合理使用
addToBackStack()
管理返回棧 - 為 Fragment 添加標(biāo)簽,便于查找:
.add(R.id.container, fragment, "TAG")
高級用法
1. Fragment 參數(shù)傳遞
// 創(chuàng)建Fragment時傳遞參數(shù) public static MyFragment newInstance(String param) { MyFragment fragment = new MyFragment(); Bundle args = new Bundle(); args.putString("key", param); fragment.setArguments(args); return fragment; } // 在Fragment中獲取參數(shù) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { String param = getArguments().getString("key"); } }
2. 使用 Navigation 組件管理 Fragment
// 在build.gradle中添加依賴 implementation "androidx.navigation:navigation-fragment:2.3.5" // 使用NavController導(dǎo)航 NavController navController = Navigation.findNavController(view); navController.navigate(R.id.action_to_next_fragment);
到此這篇關(guān)于Android Fragment 的使用小結(jié)的文章就介紹到這了,更多相關(guān)Android Fragment 使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Android入門教程之Fragment的具體使用詳解
- Android中PreferenceFragment的使用詳解
- AndroidX下使用Activity和Fragment的變化詳解
- 實例講解Android Fragment的兩種使用方法
- Android使用ViewPager快速切換Fragment時卡頓的優(yōu)化方案
- Android Studio使用ViewPager+Fragment實現(xiàn)滑動菜單Tab效果
- Android使用Scroll+Fragment仿京東分類效果
- Android使用fragment實現(xiàn)左側(cè)導(dǎo)航
- Android開發(fā)教程之Fragment定義、創(chuàng)建與使用方法詳解【包含Activity通訊,事務(wù)執(zhí)行等】
- 詳解Android 在 ViewPager 中使用 Fragment 的懶加載
- Android使用TabLayout+Fragment實現(xiàn)頂部選項卡
- Android使用TabLayou+fragment+viewpager實現(xiàn)滑動切換頁面效果
相關(guān)文章
Android中webview與JS交互、互調(diào)方法實例詳解
這篇文章主要介紹了Android中webview與JS交互、互調(diào)方法實例詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03Android實現(xiàn)ListView數(shù)據(jù)動態(tài)加載的方法
這篇文章主要介紹了Android實現(xiàn)ListView數(shù)據(jù)動態(tài)加載的方法,通過ListView控件綁定setOnScrollListener方法簡單實現(xiàn)動態(tài)加載數(shù)據(jù)的功能,需要的朋友可以參考下2016-01-01Android中實現(xiàn)在矩形框中輸入文字顯示剩余字?jǐn)?shù)的功能
在矩形輸入框框中輸入文字顯示剩余字?jǐn)?shù)的功能在app開發(fā)中經(jīng)常會見到,今天小編就通過實例代碼給大家分享android實現(xiàn)輸入框提示剩余字?jǐn)?shù)功能,代碼簡單易懂,需要的朋友參考下吧2017-04-04