一、创建FirstActivity
1、新建Android Studio的工程项目
2、在java文件下新建一个Activity,鼠标点到java文件,右键New-Activity-Empty Activity,命名,一定要选择Java语言!!!最后点击finish创建完成。
3、(很重要!!!)在AndroidManifest.xml文件中将<intent-filter>放到新建的Activity(此处为FirstActivity)下面。不然运行的时候就只会运行MainActivity里面的内容。
新建FirstActivity之后自动配置的语句位置
我们自行修改(将<intent-filter>放到新建的Activity下面)之后的位置
二、设置activity_first.xml文件的布局
添加TextView控件显示一段文字,Button控件作为跳转按钮,编辑完成后记得在FirstActivity.java文件中绑定该布局文件哦!
<?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"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="你猜猜跳转之后有什么?"/>
<Button
android:id="@+id/btnJump"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="快点我瞧瞧后面有啥"/>
</LinearLayout>
三、跳转之后的页面设计
1、同样,要实现跳转之后的页面显示也需要创建一个Activity(此处我命名为SecondActivity),创建过程如上所述。创建完成后确保 AndroidManifest.xml中语句如下图所示:
2、与SecondActivity同时建立的还有activity_second.xml文件(自动创建) ,我们在该布局文件中放置TextView控件显示文本信息以及ImageView控件显示图片信息(图片下载好复制粘贴到drawable文件下)。代码设计如下:
<?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"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="哈哈哈哈我好喜欢你呀!!!"
android:textSize="30dp"
android:textColor="#9C27B0"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/zzw1"/>
</LinearLayout>
编辑完成之后记得在SecondActivity.java文件中绑定该布局哦!
四、利用Intent实现跳转
需要在FirstActivity.java中注册跳转按钮的监听器,同时创建Intent实例并启动它。在Intent构造方法中需要传入两个参数,一个是当前的Activity实例(即我们创建的第一个FirstActivity),另一个是目标Activity(即SecondActivity)的class对象。最后调用startActivity()方法传入Intent。
在FirstActivity.java编辑代码如下:
package com.example.intent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Button btnJump=findViewById(R.id.btnJump);
btnJump.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
}
五、运行结果
左图为打开App的第一个界面,点击界面按钮之后则会跳转到右图的界面进行显示。
大家也赶紧来试试吧!