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

相关推荐
小蜜蜂嗡嗡17 分钟前
flutter namespace问题
android·flutter
Cat God 00719 分钟前
MySQL-查漏补缺版(六:MySQL-优化)
android·数据库·mysql
QING6181 小时前
Jetpack Compose Brush API 简单使用实战 —— 新手指南
android·kotlin·android jetpack
Swizard1 小时前
别让 AI 假装在工作:Android "Vibe Coding" 的生存指南
android·java·vibe coding
电饭叔2 小时前
《python语言程序设计》2018版--第8章14题利用字符串输入作为一个信用卡号之一(Luhn算法解释)
android·java·python
QING6182 小时前
Jetpack Compose Brush API 详解 —— 新手指南
android·kotlin·android jetpack
Huanzhi_Lin2 小时前
安卓连接夜神模拟器命令及原理
android
AllBlue3 小时前
unity调用安卓方法
android·unity·游戏引擎
PWRJOY3 小时前
Android Studio中安卓模拟器打不开,报错The emulator process for AVD has terminated
android·ide·android studio
凛_Lin~~4 小时前
安卓 Java线程八股文 (线程、多线程、线程池、线程安全)
android·java·开发语言