二十四、Fragment(静态添加FragMent)

1. 具备生命周期(很像一个子activity)

2. 必须委托在activity中才能运行

一、实现静态添加 FragMent

1.右键包=》NEW => FragMent (选择对应的fragment)

2.编辑页面展示代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".BlankFragment1">
    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="@string/hello_blank_fragment" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="how are you 1" />
</LinearLayout>

3.编辑 “ BlankFragment1 ” 类的相关方法,如下图所示:在 onCreateView 方法中,进行点击事件的绑定

package com.example.myapplication;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class BlankFragment1 extends Fragment {

    private View root;
    private TextView textview;
    private Button button;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (root==null){
            root = inflater.inflate(R.layout.fragment_blank1,container,false);
        }
        textview = root.findViewById(R.id.textview);
        button=root.findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textview.setText("Yes ,I am fine 1");
            }
        });


        return  root;
    }
}

4.主程序的调用(只需要在页面中创建执行标签就可以)

注意:1. 必须设定 id 属性的值

   2. name属性跟随需要绑定的 FragMent 页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!--fragment 设置绑定-->
    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.myapplication.BlankFragment1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <fragment
        android:name="com.example.myapplication.BlankFragment2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/fragment2"/>

</LinearLayout>

  

posted @ 2022-03-30 14:26  搬砖工具人  阅读(123)  评论(0编辑  收藏  举报