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

相关推荐
撩得Android一次心动35 分钟前
Android Navigation 组件全面讲解
android·jetpack·navigation
向阳是我39 分钟前
Flutter Android 编译错误修复:JVM Target Compatibility 不一致问题记录
android·jvm·flutter
Kapaseker43 分钟前
我想让同事知道我很懂 Compose 怎么办?
android·kotlin
小肝一下1 小时前
3. 数据类型
android·数据库·mysql·adb
a2591748032-随心所记1 小时前
android拆解super.img内容
android·linux·运维·服务器
Mr_pyx1 小时前
MySQL性能优化:深入理解索引原理与查询优化实战
android
恋猫de小郭1 小时前
Flutter 凉了没?Flutter 2026 的未来行程和规划,一些有趣的变化
android·前端·flutter
帅次1 小时前
Android 高级工程师专题深挖:WebView、Context 与初始化链
android·binder·webview·zygote·web app·dalvik
y小花1 小时前
安卓音频低延时与AAudio
android·音视频
Jwest20211 小时前
佳维视工业安卓一体机在医生移动查房车中的应用
android