展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

Activity创建与跳转

  • layout目录下新建activity_main2.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text2"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • 修改strings.xml
<resources>
    <string name="app_name">demo</string>

    <!-- 添加如下 -->
    <string name="text2">Activity Main 2</string>
</resources>
  • 新建MainActivity2
package com.example.demo;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity2 extends AppCompatActivity {

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

}
  • AndroidManifest.xml中添加如下
<activity android:name=".MainActivity2" />
  • 修改activity_main.xml,编写添加按钮
<Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转"
        tools:ignore="MissingConstraints" />
  • 修改MainActivity
package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
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 button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            }
        });

    }
}
  • 启动测试
posted @ 2024-07-31 06:51  DogLeftover  阅读(4)  评论(0编辑  收藏  举报