Android Fragment的静态注册和动态注册创建步骤

一、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);
  }
}

演示:

二、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);
  }
}

演示:

总结

以上所述是小编给大家介绍的Android Fragment的静态注册和动态注册创建步骤,希望对大家有所帮助!

(0)

相关推荐

  • Android 多层嵌套后的 Fragment 懒加载实现示例

    多层嵌套后的 Fragment 懒加载 印象中从 Feed 流应用流行开始,Fragment 懒加载变成了一个大家都需要关注的开发知识,关于 Fragment 的懒加载,网上有很多例子,GitHub 上也有很多例子,就连我自己在一年前也写过相关的文章.但是之前的应用可能最多的是一层 Activity + ViewPager 的 UI 层次,但是随着页面越来越复杂,越来越多的应用首页一个页面外层是一个 ViewPager 内部可能还嵌套着一层 ViewPager,这是之前的懒加载就可能不那么好用了

  • Android中Fragment的基本用法示例总结

    前言 fragment 可认为是一个轻量级的Activity,但不同与Activity,它是要嵌到Activity中来使用的,它用来解决设备屏幕大小的不同,主要是充分利用界面上的空间,如平板上多余的空间.一个Activity可以插入多个Fragment,可以认为Fragment就是Activity上的一个View. 本文主要介绍了关于Android中Fragment的基本用法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 一.fragment管理 在activity动态加载f

  • Android fragment实现多个页面切换效果

    现在的APP首页大部分屏幕的下方显示一行Tab标签选项,点击不同的标签就可以切换到不同的界面.如下图: 我们之前都是用TabHost来实现,但是殊不知,TabHost并非是那么的简单,它的可扩展性非常的差,不能随意地定制Tab项显示的内容,而且运行还要依赖于ActivityGroup.ActivityGroup原本主要是用于为每一个TabHost的子项管理一个单独的Activity,但目前已经被废弃了.下面就借助Fragment来完成类似于TabHost一般的效果. 先实现主界面布局main_l

  • 深入Android中BroadcastReceiver的两种注册方式(静态和动态)详解

    今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来接收来自系统和应用中的广播.在Android系统中,广播体现在方方面面,例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能:当网络状态改变时系统会产生一条广播,接收到这条广播就能及时地做出提示和保存数据等操作:当电池电量改变时,系统会产生一条广播,接收到这条广播就能在电量低时告知用户

  • Android使用TabLayou+fragment+viewpager实现滑动切换页面效果

    TabLayou 主要实现的是标题头的 滑动 这个 控件 类似于 ScrollView XML中的布局 <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <android.support.design.widget.TabLayout a

  • Android 使用Fragment模仿微信界面的实例代码

    什么是Fragment 自从Android 3.0中引入fragments 的概念,根据词海的翻译可以译为:碎片.片段.其目的是为了解决不同屏幕分辩率的动态和灵活UI设计.大屏幕如平板小屏幕如手机,平板电脑的设计使得其有更多的空间来放更多的UI组件,而多出来的空间存放UI使其会产生更多的交互,从而诞生了fragments . fragments 的设计不需要你来亲自管理view hierarchy 的复杂变化,通过将Activity 的布局分散到frament 中,可以在运行时修改activit

  • Android的广播Receiver动态注册和静态注册示例

    广播接收器注册一共有两种形式 : 静态注册和动态注册. 两者及其接收广播的区别: 1.动态注册的广播 永远要快于 静态注册的广播,不管静态注册的优先级设置的多高,不管动态注册的优先级有多低. 2.动态注册广播不是 常驻型广播 ,也就是说广播跟随activity的生命周期.注意: 在activity结束前,移除广播接收器. 静态注册是常驻型 ,也就是说当应用程序关闭后,如果有信息广播来,程序也会被系统调用自动运行. 3.在同一个优先级下,谁先启动的快,谁将先接收到广播. 下面这个Demo,界面如下

  • Android Fragment的静态注册和动态注册创建步骤

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

  • Oracle静态注册与动态注册详解

    一.概述: Oracle的注册就是将数据库作为一个服务注册到监听程序.客户端不需要知道数据库名和实例名,只需要知道该数据库对外提供的服务名就可以申请连接到这个数据库.这个服务名可能与实例名一样,也有可能不一样. 在数据库服务器启动过程中,数据库服务器会向监听程序注册相应的服务(无论何时启动一个数据库,默认地都有两条信息注册到监听器中:数据库服务器对应的实例和服务.) 相当于是这样:在数据库服务器和客户端之间有一监听程序(Listener),在监听程序中,会记录相应数据库对应的服务名(一个数据库可

  • JavaScript事件概念详解(区分静态注册和动态注册)

    js中的事件 什么是事件?事件是电脑输入设备与页面进行交互的响应,我们称之为事件 事件类型 鼠标单击:例如单击button.选中checkbox和radio等元素:鼠标进入.悬浮或退出页面的某个热点:例如鼠标停在一个图片上方或者进入table的范围: 键盘按键:当按下按键或释放按键时: HTML事件:例如页面body被加载时:在表单中选取输入框或改变输入框中文本的内容:例如选中或修改了文本框中的内容: 突变事件:主要指文档底层元素发生改变时触发的事件,如DomSubtreeModified(DO

  • Oracle Listener 动态注册 与 静态注册

    一.什么是注册 注册就是将数据库作为一个服务注册到监听程序.客户端不需要知道数据库名和实例名,只需要知道该数据库对外提供的服务名就可以申请连接到数据库.这个服务名可能与实例名一样,也有可能不一样. 在数据库服务器启动过程中,数据库服务器会向监听程序注册相应的服务(无论何时启动一个数据库,默认地都有两条信息注册到监听器中:数据库服务器对应的实例和服务.) 相当于是这样:在数据库服务器和客户端之间有一监听程序(Listener),在监听程序中,会记录相应数据库对应的服务名(一个数据库可能对应有多个服

  • Android Fragment(动态,静态)碎片详解及总结

    Android Fragment(动态,静态)碎片详解 一.Fragment的相关概念(一)Fragment的基础知识 Fragment是Android3.0新增的概念,中文意思是碎片,它与Activity十分相似,用来在一个 Activity中描述一些行为或一部分用户界面.使用多个Fragment可以在一个单独的Activity中建 立多个UI面板,也可以在多个Activity中使用Fragment. Fragment拥有自己的生命 周期和接收.处理用户的事件,这样就不必在Activity写一

  • Android应用开发中Fragment的静态加载与动态加载实例

    1.Fragment的静态使用 Fragment是作为Activity的UI的一部分,它内嵌在Activity中,多个Fragment可以把一个Activity分成多个部分,这在大屏幕手机或者平板电脑中会比较多的用到,这样就不用使用多个Activity来切换这么麻烦了.当然Fragment也可以不显示,只在后台处理一些数据,这篇文章中就暂时不谈到这个.以下来看怎么静态地在Activity的布局文件中添加Fragment. 自定义的Fragment通常要继承Fragment这个类,也有一些特殊的是

  • Android 动态注册监听网络变化实例详解

    Android 动态注册监听网络变化实例详解 新建一个BroadcastTest项目,然后修改MainActivity中的代码,如下: public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle

  • C语言JNI的动态注册详解

    目录 总结 JNI的静态注册就是Javah生成头文件,本章第一篇已经讲过,现在我们来讲讲第二种方式,JNI动态注册.首先是module的build.gradle: android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { applicationId "com.jhzl.a7_jni_2way" minSdkVersion 21 targetSdkVersion 30 versi

  • Android碎片fragment实现静态加载的实例代码

    静态加载好后的界面如下,两个碎片分别位于一个活动的左边和右边: 左边和右边分别为一个碎片,这两个碎片正好将一整个活动布满.一个活动当中可以拥有多个碎片,碎片的含义就是可以在同一个UI界面下,将这个界面分成好几个界面,并且可以分别更新自己的状态,如果没有碎片,那么如果你想要单独在某一个区域实现活动的"跳转"就不可能了,因此我们可以引入碎片,这样就可以在这个区域单独进行碎片的跳转.在利用底部标题栏进行首页UI的切换的时候就需要用到碎片,因此碎片在安卓开发当中十分广泛,这篇博客将会与你讲解如

随机推荐