一、fragment静态注册创建方法及步骤

1.创建一个StaticFragment.java文件继承Fragment类和一个static_fragment.xml文件完成fragment的布局。在StaticFragment.java中重载onCreateView(……)方法,通过调用inflater.inflate(……)方法并传入布局资源ID生成fragment的视图资源,并绑定static_fragment.xml中的相关组件然后实现其功能。实现代码如下:

static_fragment.xml

<?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"    tools:context=".StaticFragment"    android:orientation="vertical">    <Button        android:id="@+id/btn_fm"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="这是fragment静态注册"        android:textAllCaps="false">            </Button>    <EditText        android:id="@+id/et_fm"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入你要改变的内容:">            </EditText></LinearLayout>

StaticFragment.java

package com.example.myapplication;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;public class StaticFragment extends Fragment {         private Button mBtnFm;    private EditText mEtFm;    @Nullable    @Override    public View onCreateView(@NonNull LayoutInflater inflater,                             @Nullable ViewGroup container,                             @Nullable Bundle savedInstanceState) {             //fragment的视图资源是直接通过调用inflater.inflate(……)方法并传入布局资源ID生成的。        View v = inflater.inflate(R.layout.static_fragment,                                  container,false);        mEtFm = v.findViewById(R.id.et_fm);        mBtnFm = v.findViewById(R.id.btn_fm);        mBtnFm.setOnClickListener(new View.OnClickListener() {                 @Override            public void onClick(View v) {                     mBtnFm.setText(mEtFm.getText().toString());            }        });        return v;    }}

2.在主布局activity_main.xml文件中绑定fragment布局文件。实现代码如下:

activity_main.xml

<?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"    tools:context=".MainActivity"    android:orientation="vertical">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="这是主布局"        android:textColor="@color/colorAccent"        android:textSize="30sp">    </TextView>    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="下面是fragment的布局"        android:textColor="@color/colorPrimaryDark"        android:textSize="30sp">    </TextView>    <fragment        android:id="@+id/static_fm"        android:name="com.example.myapplication.StaticFragment"        android:layout_width="match_parent"        android:layout_height="wrap_content">    </fragment></LinearLayout>

注意:布局文件中加fragment节点,name属性必须填写完整的路径

MainActivity.java

package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {         @Override    protected void onCreate(Bundle savedInstanceState) {             super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}

演示:


链接:百度网盘下载 提取码:wqt1

二、fragment动态注册创建方法及步骤

1.新建一个项目,创建2个Fragment继承类分别为MyFragment1.java和MyFragment2.java,然后创建2个布局文件分别为fragment1.xml和fragment2.xml.详细代码如下:

fragment1.xml

<?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"    tools:context=".MyFragment1"    android:gravity="center"    android:background="@color/colorPrimaryDark">    <TextView        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:gravity="center"        android:text="@string/hello_blank_fragment"        android:textSize="30sp"        android:textAllCaps="false"        android:textColor="#F70505">    </TextView></LinearLayout>

MyFragment1.java

package com.example.myapplication;import android.content.Context;import android.net.Uri;import android.os.Bundle;import androidx.fragment.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class MyFragment1 extends Fragment {         @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {             // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment1, container, false);    }}

fragment2.xml

<?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"    tools:context=".MyFragment2"    android:gravity="center"    android:background="@color/colorAccent">    <TextView        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:gravity="center"        android:text="@string/hello_blank_fragment"        android:textSize="30sp"        android:textAllCaps="false"        android:textColor="#03FAE3">    </TextView></LinearLayout>

MyFragment2.java

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;public class MyFragment2 extends Fragment {         @Override    public View onCreateView(LayoutInflater inflater,                             ViewGroup container,                             Bundle savedInstanceState) {             // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment2, container, false);    }}

上述代码与静态创建的区别不大。
2.以代码的形式将fragment添加到activity需要在activity里直接调用FragmentManager。

FragmentManager fm = getSupportFragmentManager();

然后通过代码块:

FragmentTransaction ts = fm.beginTransaction();Fragment mfg1 = new MyFragment1();ts.add(R.id.fragment_container,mfg1);ts.commit();

提交一个fragment事务。其核心是ts.add(……)方法。
详细代码如下:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"    tools:context=".MainActivity">    <LinearLayout        android:id="@+id/linear"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:layout_alignParentBottom="true">        <Button            android:id="@+id/btn_dy1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="fragment1"            android:textColor="@color/colorAccent"            android:textSize="30sp">        </Button>        <Button            android:id="@+id/btn_dy2"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="fragment2"            android:textColor="@color/colorPrimaryDark"            android:textSize="30sp">        </Button>    </LinearLayout>    <FrameLayout        android:id="@+id/fragment_container"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_above="@id/linear">    </FrameLayout></RelativeLayout>

注意:fragment模块一般用FrameLayout布局承载

MainActivity.java

package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.Fragment;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentTransaction;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener {         private Button mBtnDy1;    private Button mBtnDy2;    FragmentManager fm;    Fragment mfg1;    Fragment mfg2;    @Override    protected void onCreate(Bundle savedInstanceState) {             super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        fm = getSupportFragmentManager();        mBtnDy1 = findViewById(R.id.btn_dy1);        mBtnDy2 = findViewById(R.id.btn_dy2);        mBtnDy1.setOnClickListener(this);        mBtnDy2.setOnClickListener(this);    }    @Override    public void onClick(View v) {             clearSelection();//清除按钮状态        FragmentTransaction ts = fm.beginTransaction();        hideFragments(ts);        switch (v.getId()){                 case R.id.btn_dy1:                mBtnDy1.setBackgroundColor(0xff0000ff);                if(mfg1 == null){                         mfg1 = new MyFragment1();                    ts.add(R.id.fragment_container,mfg1);                }else {                         ts.show(mfg1);                }                break;            case R.id.btn_dy2:                mBtnDy2.setBackgroundColor(0xff0000ff);                if(mfg2 == null){                         mfg2 = new MyFragment2();                    ts.add(R.id.fragment_container,mfg2);                }else {                         ts.show(mfg2);                }                break;                default:                    break;        }        ts.commit();    }//    将所有的Fragment都置为隐藏状态。    private void hideFragments(FragmentTransaction transaction) {             if (mfg1 != null) {                 transaction.hide(mfg1);        }        if (mfg2 != null) {                 transaction.hide(mfg2);        }    }//     清除掉所有的选中状态。    private void clearSelection() {             mBtnDy1.setBackgroundColor(0xffffffff);        mBtnDy2.setBackgroundColor(0xffffffff);    }}

演示:


链接:百度网盘下载 提取码:75lv

相关推荐:
Android——从Fragment跳转到其他Activity的简单实例
Android——fragment argument的使用

更多相关文章

  1. Android(安卓)NDK开发 Cmake环境调用 so文件
  2. Android(安卓)Studio Git .gitignore规则不生效的原因
  3. ListView的Adapter使用(绑定数据) 之 自定义每一项的布局去绑定
  4. android--由文件名获取文件Id的两种方法
  5. 使用gradle打包签名及混淆的apk
  6. Android(安卓)中能够作为 Log 开关的一些操作以及安全性浅谈
  7. Android布局中ScrollView与ListView的冲突
  8. 当android里一堆button,用数组来循环建立并且操作每个button
  9. android studio中使用NDK开发C++

随机推荐

  1. 【Android】android的基本UI操作(1)
  2. Android(安卓)User Interface之Text Fiel
  3. Android系列之利用SharedPreferences是否
  4. Android引路蜂地图开发示例:第一个地图应
  5. Android(安卓)开发简介
  6. Android全屏与非全屏问题
  7. Android-Charts,Android图形图表控件
  8. 【Android导航决 站在巨人的肩膀上】进阶
  9. android flutter 混合开发初探
  10. 【基于zxing的编解码实战】zxing项目源码