【Android四大组件之Activity学习笔记】

概要

1.Activity概述
2.Activity的(创建+配置),(启动+关闭)
3.多个Activity的交互使用
4.Fragment

1. Activity概述

Activity本质:Android手机或电脑上的一屏

1.1Activity的四种状态:

1.运行状态(可见):app等应用在正常显示运行的状态。
2.暂停状态(可见):一般情况是弹出一个询问对话框时常处于暂停状态。
3.停止状态:退出该app或页面后的状态。
4.销毁状态:将该活动在设置中强制停止后处于该状态。

1.2Activity的生命周期:

activity通过调用不同的方法来完成生命周期的演绎。
生命周期

2. Activity的(创建+配置),(启动+关闭)

关于Activity整个活动流程,笔者从以下(创建,配置,启动,关闭)几个方面进行阐述。

2.1(创建+配置)Activity

方案1(自动配置):

在当前目录下点击new,创建activity,选择样式,创建成功后该相关配置自动生成。

方案2(手动配置):
1.创建集成自Activity的Activity。
2.重写需要的回调方法(常见onCreate方法)
3.设置要显示的视图(设置指定的布局文件)

package com.example.activity;

import android.app.Activity;
import android.os.Bundle;

import androidx.annotation.Nullable;

public class test1 extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//设置视图
    }
}

此时如果直接运行就会报错。
报错
我们需要去菜单文件进行配置

//在菜单文件中添加该activity
        <activity
            android:name=".test"
            android:exported="false" />

2.2(启动+关闭)Activity

1.启动Activity的两种方式
将其作为入口Activity或将其作为其他Activity
①入口activity启动方式:
需要在AndroidManifest.xml进行相应配置
(常用于单个activity的项目)
Activity通过Intent来表达自己的“意图”。
意图

<intent-filter>
		//1.将一个activity指定为程序的主体对象
        <action android:name="android.intent.action.MAIN" />
        //2.在什么样的环境下该动作会被响应,这行代码将一个activity作为一个程序的启动项
        //当应用运行的时候就会自动启动该项。
        <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

②其他activity启动方式:
startActivity()方法
(常用于多个activity中)
案例过程:创建两个activity,实现从活动1按钮跳转到活动2。

//activity跳转核心代码
package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.telecom.Call;
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);
        //1.获取按钮组件并添加点击事件
        Button button = (Button) findViewById(R.id.btn1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击启动对象需要创建一个Intent对象,两个参数(上下文对象,需要启动的activity的class对象)
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            }
        });

    }
}

2.关闭Activity的方式
finish()方法
关闭当前activity

//添加按钮点击事件关闭该activity
package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity2 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button button = findViewById(R.id.btn2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }
}

注意:如果执行finish()方法的活动不是主活动的话,那么如果关闭当前activity则返回到调用该activity的活动页面中。

实际开发技巧:
刷新当前的activity(手机刷新当前屏幕的功能):

//Android Studio默认继承AppCompatActivity(有Bar的),使用onCreate(null)无法刷新。
//1、当前Activity要继承Activity,而不是默认的AppCompatActivity
//2、使用onCreate(null);刷新页面

onCreate(null);//在activity中调用该方法实现刷新

2.3 Activity实例

实例:模拟登录界面实现忘记密码页面跳转功能。
点击上面图片执行刷新。
点击忘记密码跳转到指定页面。
登录页面
点击返回主页回到上一个activity
跳转页面

//需要编辑的页面有以下四个,其中按钮组件可以由<imagebutton>来模拟图片按键。
1.MainActivity.java
2.register_password.java
3.activity_main.xml
4.activity_register_password.xml

以下为其java详细逻辑代码(xml文件略)

//MainActivity.java代码
package com.example.register;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

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

        ImageView imageView = findViewById(R.id.image);
        TextView textView = findViewById(R.id.forget);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, register_password.class);
                startActivity(intent);
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onCreate(null);
                Toast.makeText(MainActivity.this, "已刷新", Toast.LENGTH_SHORT).show();
            }

        });

    }
}
//register_password.java
package com.example.register;

import androidx.appcompat.app.AppCompatActivity;

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

public class register_password extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_password);
        Button button = findViewById(R.id.back);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}

3.多个Activity的交互使用

3.1Bundle在Activity之间交换数据

使用Bundle在Activity之间交换数据
Intent使用场景:我们在一个activity中启动另一个activity并传入数据,但Intent本身不具备保存数据的能力。我们需要引入新的对象Bundle来实现。
Bundle:本质是键值对的组合。(key,value),通过key来获取value值。
本质
实例:淘宝页面填写并显示收货地址的功能。
实例
点击保存后
跳转另一页面

//MainActivity.java

package com.example.bundleactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.btn1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1.获取姓名,地址,手机号码,邮箱等信息
                String name = ((EditText)findViewById(R.id.et_name)).getText().toString();
                String site = ((EditText)findViewById(R.id.et_site)).getText().toString();
                String number = ((EditText)findViewById(R.id.et_number)).getText().toString();
                String email = ((EditText)findViewById(R.id.et_email)).getText().toString();

                if (!"".equals(name) && !"".equals(site) && !"".equals(number) && !"".equals(email)) {
                    //创建Intent对象实现跳转
                    Intent intent = new Intent(MainActivity.this, addressActivity.class);
                    //创建Bundle对象用于保存信息
                    Bundle bundle = new Bundle();
                    bundle.putCharSequence("name", name);
                    bundle.putCharSequence("site", site);
                    bundle.putCharSequence("number", number);
                    bundle.putCharSequence("email", email);
                    //使用intent调用bundle进行数据传输
                    intent.putExtras(bundle);
                    //调用startActivity(intent)传输到另一个activity
                    startActivity(intent);


                } else {
                    Toast.makeText(MainActivity.this, "请将收货地址信息填写完整", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }
}

其对应的xml文件

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="-28dp"
        tools:layout_editor_absoluteY="0dp">

        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="姓名"
            android:inputType="text"
            android:lines="1" />

        <EditText
            android:id="@+id/et_site"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="地址"
            android:inputType="text"
            android:lines="1" />

        <EditText
            android:id="@+id/et_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="手机号码"
            android:inputType="text"
            android:lines="1" />

        <EditText
            android:id="@+id/et_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="邮箱"
            android:inputType="text"
            android:lines="1" />

        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginTop="20dp"
            android:layout_marginRight="20dp"
            android:background="#FF5000"
            android:text="保存" />


    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

其跳转目标activity

//addressActivity.java
package com.example.bundleactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class addressActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        //1.在该activity中接收main_activity中的数据
        Intent intent = getIntent();
        //2.获取其bundle
        Bundle bundle = intent.getExtras();
        //3.获取bundle中传输来的信息进行接收
        String name = bundle.getString("name");
        String site = bundle.getString("site");
        String number = bundle.getString("number");
        String email = bundle.getString("email");
        //4.获取该activity需要输出的文本框
        TextView tv_name = (TextView) findViewById(R.id.name);
        TextView tv_site = (TextView) findViewById(R.id.site);
        TextView tv_number = (TextView) findViewById(R.id.number);
        TextView tv_email = (TextView) findViewById(R.id.email);
        //5.将获取到的信息输入到对应的文本框中
        tv_name.setText(name);
        tv_site.setText(site);
        tv_number.setText(number);
        tv_email.setText(email);
    }
}

对饮的activity_address.xml

//activity_address.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".addressActivity">

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

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp" />

        <TextView
            android:id="@+id/site"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp" />

        <TextView
            android:id="@+id/number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp" />

        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

3.2 调用另一个Activity并返回结果

适用场景:从一个activity中调用另一个activity并选择一些内容,之后自动返回到第一个activity当中。

//使用 startActivityForResult()方法进行实现。两个参数:(启动指定的activity的intent对象,表明请求来源的请求码)
public void startActivityForResult(Intent intent,int requestCode){}
//以上方法已废弃很久了,现在使用替代方法
registerForActivityResult()

实例:模拟选择头像功能(提前准备好照片放入)
主页面

//MainActivity.java(主函数)
package com.example.otheractivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends Activity {

    //3.重写方法,查看请求码和返回码是否一致,如果一致的话就获取返回内容
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == 0x11) {
            //定义Bundle对象进行获取
            assert data != null;
            Bundle bundle = data.getExtras();
            assert bundle != null;
            int imageId = bundle.getInt("imageId");
            //获取设置头像图片位置并设置图片
            ImageView imageView = findViewById(R.id.imageView);
            imageView.setImageResource(imageId);

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1.实例化intent对象
                Intent intent = new Intent(MainActivity.this, headActivity.class);
                //2.使用目标方法进行设置请求码
                startActivityForResult(intent, 0x11);
            }
        });


    }
}

选择头像页面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    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="200dp"
        android:background="@drawable/sea"
        android:orientation="vertical"
        tools:ignore="UselessParent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:adjustViewBounds="true"
            android:maxWidth="75dp"
            android:maxHeight="75dp"
            android:scaleType="fitXY"
            android:src="@drawable/flower"
            android:importantForAccessibility="no" />

        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:text="选择头像" />

    </LinearLayout>

</LinearLayout>

headActivity.java选择头像文件

//headActivity.java
package com.example.otheractivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class headActivity extends Activity {
    //定义数组用来存储图片
    public int[] imageId = new int[]{R.drawable.car, R.drawable.car,
            R.drawable.flower, R.drawable.sea, R.drawable.heart};

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

        //1.为网格视图指定适配器
        GridView gridView;
        gridView = (GridView) findViewById(R.id.gridView);
        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return imageId.length;
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ImageView imageView;
                if (convertView == null) {
                    imageView = new ImageView(headActivity.this);
                    imageView.setAdjustViewBounds(true);
                    imageView.setMaxHeight(150);
                    imageView.setMaxHeight(158);
                    imageView.setPadding(5, 5, 5, 5);
                } else {
                    imageView = (ImageView) convertView;
                }
                imageView.setImageResource(imageId[position]);
                return imageView;
            }
        };
        //2.设置适配器
        gridView.setAdapter(adapter);
        //3.添加选项被点击的监听器
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = getIntent();
                //4.添加Bundle保存数据
                Bundle bundle = new Bundle();
                //5.将选中的图片保存到bundle当中通过putInt(key,position选中数组位置)
                bundle.putInt("imageId", imageId[position]);
                //6.将bundle保存到intent当中
                intent.putExtras(bundle);
                //7.设置一个返回码,一般和请求码是一样的
                setResult(0x11,intent);
                finish();
            }
        });

    }
}

选择头像页面
选择头像页面布局

//选择头像布局
<?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=".headActivity">

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:horizontalSpacing="3dp"
        android:numColumns="4"
        android:verticalSpacing="3dp">
    </GridView>

</RelativeLayout>

最终实现替换

4.Fragment(碎片)

意义:与activity类似,在一个activity中描述一些行为或者是一部分用户界面。多个activity 中重用该fragment。也可以使用Fragment在一个单独的activity建立单独的UI面板。
例:微信用户界面,在一个activity中包含了多个fragment.选择微信的下标进行不同fragment的切换。

4.1Fragement的生命周期

一个fragment必须被镶嵌到一个activity中,其生命周期收到所在载体的生命周期影响。
例子:activity就像水塘的水,fragment就像水塘中的🐟。水无则🐟无。

fragment的生命周期
创建Fragment步骤:
1.创建Fragment的布局文件,fragement_list.xml
2.创建java类继承Fragment

//layout中创建newlayout资源
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="welcome to our country"/>


</LinearLayout>
//创建ListFragment.java文件  方法1:
package com.example.fragmentstudy;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ListFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //1.创建碎片加载布局文件参数说明(布局文件,ViewGroup默认对象,false)
        View view = inflater.inflate(R.layout.fragment_list,container,false);
        //2.加载返回碎片
        return view;
    }
}


//方法2:
package com.example.fragmentstudy;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ListFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list,container,false);
    }
}



4.2在Activity中添加Fragement

1.方法1:直接在布局文件中添加Fragment
2.方法2:activity运行时动态添加Fragment
以方法二演示为主
activity中加载fragment

首先需要准备四个文件(鱼塘和鱼)
1.MainActivity.java
2.activity_main.xml
3.FragmentList.java
4.fragment_list.xml

//4.fragment_list.xml为碎片布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="fragmentlist is this "/>

</LinearLayout>
//3.FragmentList.java碎片java文件用于加载该布局
package com.example.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragmentList extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //加载fragment布局
        return inflater.inflate(R.layout.fragment_list,container,false);
    }
}

//2.activity_main.xml 在activity中的布局文件添加碎片
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment_container"/>

</androidx.constraintlayout.widget.ConstraintLayout>
//1.MainActivity中实现添加布局碎片的逻辑
package com.example.fragment;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

    private Fragment FragmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //1.获取FragmentManager
        FragmentManager fragmentManager = getSupportFragmentManager();
        //2.开启一个FragmentTransaction
        FragmentTransaction ft = fragmentManager.beginTransaction();
        //3.创建并添加Fragment
        FragmentList fragmentList = new FragmentList();
        ft.add(R.id.fragment_container,fragmentList);
        //4.提交事务
        ft.commit();
    }
}

4.3模拟Tab的切换功能

如遇f报错请看文章:
https://blog.csdn.net/weixin_40715900/article/details/116975712

实例页面:通过下方选项选相应的fragment(以下面两个icon为例)
图1
图2

部分相关文件(显示内容请自行添加到drawable文件夹)
所涉及到的文件
核心代码四类:
1.MainActivity.java
2.Car1_Fragment.java(其他页面fragment类似)
3.activity_main.xml
4.car1_fragment.xml(其他页面fragment类似)

1.MainActivity.java 主要逻辑代码

package com.example.tabchange;

import static com.example.tabchange.R.*;
import static com.example.tabchange.R.id.fragment;
import static com.example.tabchange.R.id.icon;

import android.app.Fragment;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //目标点击不同的icon图标,实现不同的fragment
        //1.获取四张不同的icon
        ImageView imageView = (ImageView) findViewById(R.id.icon);
        ImageView imageView1 = (ImageView) findViewById(R.id.icon1);
        ImageView imageView2 = (ImageView) findViewById(R.id.icon2);
        ImageView imageView3 = (ImageView) findViewById(R.id.icon3);
        //4.为四个icon添加事件监听器
        imageView.setOnClickListener(l);
        imageView1.setOnClickListener(l);
        imageView2.setOnClickListener(l);
        imageView3.setOnClickListener(l);


    }

    //创建事件监听器
    View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //1.创建fragmentManager对象
            FragmentManager fragmentManager = getFragmentManager();
            //2.开启一个FragmentTransaction组
            FragmentTransaction ft = fragmentManager.beginTransaction();
            //3.初始化一个Fragment对象
            Fragment f = null;
            //4.编写switch语句进行选择性显示对应的fragment
            if (v.getId() == id.icon) {
                f = new WeCar_Fragment();
            } else if (v.getId() == id.icon1) {
                f = new Car1_Fragment();
            } else if (v.getId() == id.icon2) {
                f = new Car2_Fragment();
            } else if (v.getId() == id.icon3) {
                f = new Car3_Fragment();
            } else {
                Log.d("wjj", "time out");
            }
            //5.参数(在布局文件添加的本身fragment,Fragment对象,
            ft.replace(R.id.fragment, f);
            //6.提交事务
            ft.commit();

        }
    };
}

2.Car1_Fragment.java(其他页面fragment类似)
其他Fragment请参照该方法进行定义。

package com.example.tabchange;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.app.Fragment;

public class Car1_Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.car1_fragment,null);
    }
}

3.activity_main.xml

//3.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment"
        android:name="com.example.tabchange.WeCar_Fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:src="@drawable/che" />

        <ImageView
            android:id="@+id/icon1"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:src="@drawable/che_1" />

        <ImageView
            android:id="@+id/icon2"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:src="@drawable/che_2" />

        <ImageView
            android:id="@+id/icon3"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:src="@drawable/che_3" />


    </LinearLayout>


</RelativeLayout>

4.car1_fragment.xml(其他页面fragment类似)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/car1" />

</RelativeLayout>

5.小结

本文是笔者学习Activity的时候所整理的笔记,希望能给大家学习带来帮助!!!

  • 16
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值