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 生命周期

相关推荐
xingxiliang6 小时前
深入浅出 Android CTS 视频测试:从环境搭建、用例设计到底层通信原理
android·音视频
我命由我123456 小时前
Android 开发问题:为 PDFView 设置一个带有黑色边框的背景 drawable,但边框没有生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
雨白8 小时前
深入理解 Kotlin 协程 (八):拾遗补阙,探秘官方框架的调度细节与取消闭环
android·kotlin
海天鹰10 小时前
PHP上传文件
android·开发语言·php
2501_9159184111 小时前
详解iOS App上架至App Store的全流程步骤与注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
码农coding12 小时前
android12 SystemUI之StatusBar(二)
android
Lesile14 小时前
Interview#1 历史演进:MVC · MVP · MVVM · MVI架构详解
android·android jetpack
杉氧14 小时前
Flutter 像素级还原实战:用 CustomPaint 与 Bezier 曲线手绘精致图针
android·前端·flutter
我命由我1234517 小时前
Android 在构建过程中,发现有两个依赖库都包含了相同路径的资源文件
android·java·开发语言·java-ee·kotlin·android-studio·android runtime
Coffeeee18 小时前
谷歌的一个优化建议,让我重新学了一遍Android里面如何正确处理位图
android·google·kotlin