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

相关推荐
2501_9159214332 分钟前
iOS 抓不到包怎么办?工程化排查与替代抓包方案(抓包/HTTPS/Charles代理/tcpdump)
android·ios·小程序·https·uni-app·iphone·tcpdump
诸神黄昏EX2 小时前
Android Init 系列专题【篇六:reboot & shutdown】
android
sTone873752 小时前
Android核心概念(一)minSdkVersion targetSdkVersion compileSdkVersion
android·前端
wuweikai06172 小时前
在Android设备上打开Perfetto调试日志开关
android·性能优化·perfetto
Meteors.2 小时前
安卓进阶——多媒体
android
正经教主3 小时前
【App开发】Mumu模拟器安装使用与Android Studio连接指南
android·ide·android studio
Larry_zhang双栖3 小时前
Flutter Android Kotlin 插件编译错误完整解决方案
android·flutter·kotlin
wuwu_q4 小时前
彻底讲清楚 Kotlin 的 when 表达式
android·开发语言·kotlin
木易 士心5 小时前
Android 开发核心技术深度解析
android·开发语言·python