Android——Fragment

Fragment 静态注册

xml 复制代码
	...
    <fragment
        android:id="@+id/fragment_static"
        android:name="com.example.study_android.fragment.StaticFragment"
        android:layout_width="match_parent"
        android:layout_height="60dp"/>
        
	<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="主要内容" />
        ...
java 复制代码
public class StaticFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_static, container, false);
    }
}

案例代码

Fragment 动态注册

在某些 Adapter 中返回一个一个 Fragment

java 复制代码
public class DynamicFragment extends Fragment {
    public static DynamicFragment newInstance(int position,String name, String desc) {
        DynamicFragment fragment = new DynamicFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        args.putString("name", name);
        args.putString("desc", desc);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        /*
         * container:fragment根据该容器计算宽高
         * false:是否将该fragment添加到container容器中
         * */
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

        Bundle arguments = getArguments();

        if (arguments != null) {
            TextView name = view.findViewById(R.id.name);
            TextView desc = view.findViewById(R.id.desc);
            name.setText(arguments.getString("name"));
            desc.setText(arguments.getString("desc"));
        }

        return view;
    }
}

案例代码

Fragment 生命周期

相关推荐
冬奇Lab9 小时前
PowerManagerService(下):Doze模式与电池优化
android·源码阅读
砖厂小工10 小时前
Compose 中函数引用 vs Lambda:到底该用哪个?
android
Kapaseker21 小时前
详解 Compose background 的重组陷阱
android·kotlin
黄林晴21 小时前
Kotlin 2.3.20-RC2 来了!JPA 开发者狂喜,6 大更新一文速览
android·kotlin
kymjs张涛1 天前
OpenClaw 学习小组:初识
android·linux·人工智能
范特西林2 天前
实战演练——从零实现一个高性能 Binder 服务
android
范特西林2 天前
代码的生成:AIDL 编译器与 Parcel 的序列化艺术
android
范特西林2 天前
深入内核:Binder 驱动的内存管理与事务调度
android
范特西林2 天前
解剖麻雀:Binder 通信的整体架构全景图
android
范特西林2 天前
破冰之旅:为什么 Android 选择了 Binder?
android