首页 > 其他分享 >Android studio 中fragment 的简单应用

Android studio 中fragment 的简单应用

时间:2023-04-16 15:46:16浏览次数:41  
标签:fragment Fragment studio new import Android id View

在 Android Studio 中,Fragment 是一种可重用的 UI 组件,它代表了 Activity 中的一部分界面。它类似于 Activity,但是可以被添加、删除和替换,同时可以与其他 Fragment 组合在一起形成更复杂的 UI 界面。通常情况下,Activity 由多个 Fragment 组成,每个 Fragment 都有自己的布局和功能,可以通过代码进行添加、删除和替换。
Fragment 可以看作是 Activity 中的子页面,每个 Fragment 都有自己的布局和逻辑代码,可以单独进行管理和维护。同时,Fragment 可以灵活地适应不同的屏幕尺寸和设备类型,使得应用程序在各种设备上都能够自适应。例如,可以在平板电脑上同时显示两个 Fragment,而在手机上只显示一个。
使用 Fragment 的好处有很多。其中最重要的是,它可以使应用程序的代码更加模块化和可重用,减少代码的复杂度和维护成本。另外,使用 Fragment 还可以提高应用程序的性能,因为它可以使应用程序更加灵活和高效地管理 UI 界面。
在 Android Studio 中,可以通过向项目中添加一个 Fragment 来创建一个新的 Fragment。然后,可以使用 FragmentTransaction 类来管理 Fragment 的添加、删除和替换。同时,也可以使用 FragmentManager 来管理 Fragment 的生命周期,例如创建、启动、暂停、恢复、停止和销毁等。在使用 Fragment 的过程中,还需要了解 Fragment 的一些基本概念和技术,例如 Fragment 的生命周期、Fragment 之间的通信、Fragment 的回退栈等。

创建一个新的 Fragment:

在 Android Studio 中,可以使用模板来创建一个新的 Fragment。选择 File -> New -> Fragment -> Fragment (Blank)。这将创建一个新的 Fragment 类,其中包含了一些基本的代码。
image
image
不仅会生成NewsFragment.java还有fragment_news.xml
接着再生成两个,SportsFrgment和SportsFrgment
然后会生成相应的文件和基本代码
image

编辑activity_main.xml和fragment_news.xml

activity_main.xml中创建了一个TextView显示主页,下面有三个按键

<?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">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btnNews"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="News" />

        <Button
            android:id="@+id/btnSport"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Sport"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btnScience"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Science"
            android:textStyle="bold" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainerView5"
            android:name="com.zdb.hwfrist.NewsFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:tag="mytag"
            tools:layout="@layout/fragment_news" />
    </LinearLayout>

</LinearLayout>

image

fragment_main.xml只是创建了一个TextView,用来覆盖activity_main.xml中第二个LinearLayout。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".NewsFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/news"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#673AB7"
        android:gravity="center"
        android:text="hi news"
        android:textColor="#D12E2E"
        android:textSize="34sp" />

</FrameLayout>

image
将另外两个xml也修改完成

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".ScienceFragment">

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:id="@+id/science"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#1E99D1"
        android:gravity="center"
        android:text="hi Science"
        android:textColor="#D12E2E"
        android:textSize="34sp" />

</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".SportFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/sport"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#D58613"
        android:gravity="center"
        android:text="hi Sport"
        android:textColor="#D12E2E"
        android:textSize="34sp" />


</FrameLayout>

编辑MainActivity.java

导入基本包,包括Fragment的包

package com.zdb.hwfrist;

import androidx.appcompat.app.AppCompatActivity;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

在主函数写入点击事件

Button btnnews = findViewById(R.id.btnNews);
        btnnews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                fm.beginTransaction()
                        .replace(R.id.fragmentContainerView5,  new NewsFragment(), null)
                        .setReorderingAllowed(true)
                        .addToBackStack("name")
                        .commit();
            }
        });

这段代码主要用于设置一个按钮(btnnews),并为该按钮设置一个点击事件监听器。点击按钮时,将执行以下操作:

1.从视图中获取 FragmentManager
2.开始一个新的 Fragment 事务,并替换一个指定的 fragment(R.id.fragmentContainerView5) 为一个新的 NewsFragment。
3.设置重新排序的标志,以确保操作是正确的。
4.添加事务到回退栈中,并指定回退栈的名称为 "name"。
5.提交事务以完成操作。
这段代码主要用于在按钮点击时启动一个新的 Fragment 来显示新闻内容。通过将事务添加到回退栈中,用户可以通过按下“返回”按钮返回之前的 Fragment。
完整代码

package com.zdb.hwfrist;

import androidx.appcompat.app.AppCompatActivity;

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 {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnnews = findViewById(R.id.btnNews);
        btnnews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                fm.beginTransaction()
                        .replace(R.id.fragmentContainerView5,  new NewsFragment(), null)
                        .setReorderingAllowed(true)
                        .addToBackStack("name")
                        .commit();
            }
        });
        Button btnsport = findViewById(R.id.btnSport);
        btnsport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fragmentContainerView5, new SportFragment(), null);
                ft.commit();
            }
        });
        Button btnscience = findViewById(R.id.btnScience);
        btnscience.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                fm.beginTransaction()
                        .replace(R.id.fragmentContainerView5, new ScienceFragment(), null)
                        .setReorderingAllowed(true)
                        .addToBackStack("name")
                        .commit();
            }
        });
    }
}

演示

image
image
image

标签:fragment,Fragment,studio,new,import,Android,id,View
From: https://www.cnblogs.com/bertin/p/17320800.html

相关文章

  • Android深入学习之LayoutInflater类和ViewBinding
    在build.gradle(Module)中添加viewBinding元素后,Android会自动给模块中的每个XML布局文件生成一个相应的Binding类,该Binding类名称为XML布局文件驼峰式大写+Binding后缀。以如下所示的activity_welcome.xml文件为例,对应的ActivityWelcomeBinding.java的源代码如下所示。<?xmlv......
  • Visual Studio Code开发常用的工具栏选项,查看源码技巧以及【vscode常用的快捷键】
    一、开发常用的工具栏选项1、当前打开的文件快速在左侧资源树中定位:其实打开了当前的文件已经有在左侧资源树木定位了,只是颜色比较浅2、打开太多文件的时候,可以关闭3、设置查看当前类或文件的结构OUTLINE相当于idea查看当前类或接口的结构Structure二、查看......
  • Visual Studio Code 常见的配置、常用好用插件以及【vsCode 开发相应项目推荐安装的插
    一、VsCode常见的配置1、取消更新把插件的更新也一起取消了2、设置编码为utf-8:默认就是了,不用设置了3、设置常用的开发字体:Consolas,默认就是了,不用设置了字体对开发也很重要,不同字体,字母形态都不太一样,尤其是标点符号,逗号和分号的区分,有的字体看着这两者就很像......
  • Android入门教程_废弃
    没意思,不想写了... 目录一,Android介绍Android概述什么是AndroidAndroid开发优势Android的特性可以开发什么appAndroid手机安装包apkAndroid架构https://www.runoob.com/android/android-architecture.html学习安卓需要具备哪些知识(PS+UI(优秀软件:墨刀-万兴科技......
  • Android Studio调用高德地图api
    一.搜索高德开放平台,进行注册并登录,进入到自己的控制台,打开应用管理下的我的应用,点击创建新应用。1.关于获取发布版安全码SHA1的过程如下:    打开AndroidStudio下方的Terminal,并自行找到.android在电脑中的位置,找到了之后,按照下图所示:   之后执行keytool-lis......
  • Android开发,使用的是OkHttp和Reftrofit,用的是Kotlin协程,用Kotlin写一个网络拦截器,模拟
    首先,我们需要定义一个网络拦截器类,继承自OkHttp的Interceptor接口:classLoginInterceptor:Interceptor{overridefunintercept(chain:Interceptor.Chain):Response{//模拟登录请求,这里可以根据具体情况进行修改valrequest=chain.request().ne......
  • Android MediaCodec 解码 mp4
    上篇博文:AndroidMediaCodec功能讲解本文示例源代码:MediaCodec解码播放mp4文件上篇博文中,我们讲解了MediaCodec的基础知识,本篇文章我们通过使用MediaCodec解码并播放mp4文件,来讲下MediaCodec的使用。解码并播放mp4文件主要涉及到了以下5大方面的功能:解码视频......
  • Android MediaCodec 功能讲解
    上篇博文:AndroidMediaPlayer功能讲解MediaCodec是Android系统提供的用于对音视频进行编解码的类,它通过访问底层的codec来实现编解码的功能。Codec意为编解码器。MediaCodec是Androidmedia基础框架的一部分,是比MediaPlayer更底层的实现。MediaCodec通常同MediaExt......
  • Android中GC—初探-1—触发时机和条件
    一、GC简介Java对象的创建由Allocator负责,回收由Collector负责。从AndroidO开始,对于前台应用默认的GCCollector是CC(ConcurrentCopying)Collector,与之相匹配的Allocator则是Region-basedBumpPointerAllocator(withTLAB)。二、前台应用GC何时触发1.GC触......
  • android studio 简易计算器制作
    只是记录一下代码,随意取用<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width=&quo......