Android学习之探究活动2

2.3使用Intent在活动之间穿梭

2.3.1使用显示的Intent

创建一个新的活动
在这里插入图片描述
在这里插入图片描述
更改activity_second.xml文件内容

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".SecondActivity">
    <Button
    android:id="@+id/button_2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button 2"
    tools:ignore="MissingConstraints"/>

</androidx.constraintlayout.widget.ConstraintLayout>

接下来在AndroidManifest.xml文件中注册
在这里插入图片描述

Intent是Android程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前组件想要执行动作,还可以在不同组件之间传递数据。

接下来修改主活动

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        Button button1=(Button)findViewById(R.id.button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
    }

FirstActivity.this作为上下文,传入Second-Activity.class作为活动目标。

2.3.2使用隐式的Intent

修改AndroidMainifest.xml文件

  <activity android:name=".SecondActivity">
            <intent-filter>
                <action android:name="com.example.activitytest.ACTION_START"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity

修改FirstActivity.java文件

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        Button button1=(Button)findViewById(R.id.button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("com.example.activitytest.ACTION_START");
                startActivity(intent);
            }
        });
    }

点击链接加入群聊【程序员技术交流群】:添加链接描述

发布了84 篇原创文章 · 获赞 24 · 访问量 4320

猜你喜欢

转载自blog.csdn.net/qq_41827511/article/details/104848925