欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android Fragment 的使用小結(jié)

 更新時間:2025年04月03日 10:53:03   作者:滬cares  
Fragment是Android 應(yīng)用開發(fā)中的重要組件,它代表 Activity 中的一部分 UI 或行為,可以組合多個 Fragment 在一個 Activity 中構(gòu)建多窗格 UI,并在不同 Activity 中重復(fù)使用某個 Fragment,本文給大家介紹Android Fragment 使用,感興趣的朋友一起看看吧

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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android剪貼板用法詳解

    Android剪貼板用法詳解

    這篇文章主要介紹了Android剪貼板用法詳解,以實例的形式對Android中剪貼板的各類傳值方法做了較為詳細(xì)的講述,需要的朋友可以參考下
    2014-10-10
  • Volley源碼之使用方式和使用場景詳解

    Volley源碼之使用方式和使用場景詳解

    這篇文章主要介紹了Volley源碼之使用方式和使用場景詳解,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • Android 文件選擇器詳解及實例代碼

    Android 文件選擇器詳解及實例代碼

    這篇文章主要介紹了Android 文件選擇器詳解的相關(guān)資料,并附實例代碼,需要的朋友可以參考下
    2016-10-10
  • Android編程之EditText常見操作示例

    Android編程之EditText常見操作示例

    這篇文章主要介紹了Android編程之EditText常見操作,結(jié)合實例形式分析了Android EditText光標(biāo)與文本操作相關(guān)技巧,需要的朋友可以參考下
    2017-03-03
  • 完美解決Jpush[獲取sdk版本失敗!]的問題

    完美解決Jpush[獲取sdk版本失敗!]的問題

    下面小編就為大家?guī)硪黄昝澜鉀QJpush[獲取sdk版本失敗!]的問題的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • Android中webview與JS交互、互調(diào)方法實例詳解

    Android中webview與JS交互、互調(diào)方法實例詳解

    這篇文章主要介紹了Android中webview與JS交互、互調(diào)方法實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • Android添加音頻的幾種方法

    Android添加音頻的幾種方法

    今天小編就為大家分享一篇關(guān)于Android添加音頻的幾種方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • Android實現(xiàn)ListView數(shù)據(jù)動態(tài)加載的方法

    Android實現(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-01
  • Android中實現(xiàn)在矩形框中輸入文字顯示剩余字?jǐn)?shù)的功能

    Android中實現(xiàn)在矩形框中輸入文字顯示剩余字?jǐn)?shù)的功能

    在矩形輸入框框中輸入文字顯示剩余字?jǐn)?shù)的功能在app開發(fā)中經(jīng)常會見到,今天小編就通過實例代碼給大家分享android實現(xiàn)輸入框提示剩余字?jǐn)?shù)功能,代碼簡單易懂,需要的朋友參考下吧
    2017-04-04
  • 淺析Android.mk

    淺析Android.mk

    Android.mk是Android提供的一種makefile文件,用來指定諸如編譯生成so庫名、引用的頭文件目錄、需要編譯的.c/.cpp文件和.a靜態(tài)庫文件等。要掌握jni,就必須熟練掌握Android.mk的語法規(guī)范
    2016-01-01

最新評論