【Java与智能设备】4_1 Activity的创建和跳转

掌握在Android中建立Activity的方法
掌握在Activity之间传递数据的方式

1. 概述

  1. Activity是Android应用中最重要的核心组件,每一个应用屏幕就是一个Activity;这意味着,要创建多屏幕的应用,必须创建多个Activity。
  2. Android中的Activity的使用基本上分为以下三大类问题:
    • 如何创建多屏幕(如何创建多个Activity
    • 屏幕与屏幕之间如何切换(Activity之间的跳转
    • 屏幕是何时产生何时消亡的(Activity的生命周期

2. 创建

创建新的Activity的基本流程:

  • 创建新的类继承Activity 类(src/指定包/目录下)
  • 为该Activity类绑定布局(res/layout/目录下)
  • AndroidManifest.xml文件中注册该Activity
  1. 创建新的类继承Activity 类(src/指定包/目录下)
    • 继承的类:和MainActivity继承的类一样
      androidx.appcompat.app.AppCompatActivity
      在这里插入图片描述
    • 重写onCreate方法(注意参数类型:一个参数 Bundle)
  2. 新建布局文件
    在这里插入图片描述
    绑定布局
    在这里插入图片描述
  3. AndroidManifest.xml文件中注册该Activity
    • app-manifests-AndroidManifest.xml
    • AndroidManifest.xml中的application中包含程序运行的所有组件,Activity组件需要在这里注册,否则无法使用,注册的先后顺序没有关系
    • name属性指定Activity的类型(全限定名-带包名的类名)
    • 如果在pakage有指定包名,而且该Activity直接定义在了这个包里面,则在name属性中可以直接写“.NewActivity
      在这里插入图片描述
      新创建的Activity也可以设置为主页面显示,但是一个程序中只能有一个作为主页面
      在这里插入图片描述
快捷创建Activity的方法

包上右击-new-Activity-一些模板/空Activity
快捷生成Activity
在这里插入图片描述



例子:创建联系人详细信息显示页面

可以实现点击后跳转页面,编辑后保存到主页面并关闭当前页面跳转到主页面。
在这里插入图片描述
重点是页面跳转,分为需不需要传数据,两种方式
startActivity()
startActivityForResult()

跳转的基本原理

  1. 回顾Web应用中,页面与页面之间的跳转是通过HTTP协议进行的。
    • 请求页面会向目的地页面发送一个HTTP请求(借助请求对象实现)。
    • 请求对象中内容包括(请求目的地提交数据等)
    • 目的地页面会反馈给请求页面一个HTTP响应(借助响应对象实现)。
    • 响应对象中包括(响应消息内容
  2. Android中要实现页面跳转,同样需要具备充当请求对象和响应对象的东西。
    • 在Android中,Activity与Activity之间的跳转是借助Intent对象来实现的。
      • Intent对象用来在Activity与Activity之间传递请求消息和响应消息。
      • 也就是说,Intent对象充当了HTTP协议中的请求对象和响应对象双重作用

Intent:意图对象,Activity与Activity之间跳转的中介。

发送请求的Activity页面
  1. 创建Intent对象:
    • Intent i = new Intent( );
  2. 设置请求目的地:
    • i.setClass( 上下文, 待启动的Activity.class);
    • i.setAction( 目的Activity字符串 );
  3. 携带数据(可选)
    • 直接添加基本类型参数:i.putExtra( key, value )
    • 传递类的对象(需要序列化对象后才可传递)
    • Bundle,创建复杂数据对象
      • 创建Bundle对象:Bundle b = new Bundle()
      • 为Bundle对象添加数据:b.putString(),b.putSerializable()
      • 把Bundle对象添加到Intent对象中:i.putExtra(b)
  4. 发送请求(启动新的Activity):
    • startActivity( Intent对象 );
    • startActivityForResult( Intent对象, 请求码 );
示例代码:
  1. Student.java
  2. MainActivity.java
  3. NewActivity.java
  4. activity_main.xml
  5. activity_new.xml

Student.java

package com.example.ch0401activity;

import java.io.Serializable;

//使用Intent传递该类型对象时,需要让该类实现Serializable接口
public class Student implements Serializable {
    private String name;
    private String phone;
    private String email;

    public Student() {
    }

    public Student(String name, String phone, String email) {
        this.name = name;
        this.phone = phone;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

MainActivity.java

package com.example.ch0401activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.ch0401activity.activity.NewActivity;

public class MainActivity extends AppCompatActivity {
    private String[] names = {"张三","李四","王五"};
    private ArrayAdapter adapter;//适配器
    private final int LOGIN_REQUEST = 100;
    private int currentPosition;//用于判断是哪条数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView nameListView = findViewById(R.id.lv);
        adapter = new ArrayAdapter(this,//上下文
                android.R.layout.simple_list_item_1,//布局
                names);
        nameListView.setAdapter(adapter);
        nameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Activity跳转
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,//当前
                        NewActivity.class);//目的地
                //跳转时需要携带数据,key-value
                //第一种
                intent.putExtra("name",names[position]);//变化的数据
                intent.putExtra("phone","phone123");//假数据
                intent.putExtra("email","email456");//假数据
                intent.putExtra("position",position);

                // 第二种 将数据先封装到Bundle对象,再添加到Intent对象
//                Bundle bundle = new Bundle();
//                bundle.putString("name",names[position]);
//                bundle.putString("phone","phone123");
//                bundle.putString("email","email456");
//                intent.putExtra("bundle",bundle);

                //第三种 传递自定义类型的对象
//                Student student = new Student("张三","张三phone","张三email");
//                intent.putExtra("stu",student);//此处不能直接传入Student类的对象,
                                                     // 需要让新建的类实现一个接口 Serializable

                //跳转
                // 不传递数据,并且不需要返回响应
//                startActivity(intent);
                //跳转,返回响应
                startActivityForResult(intent,LOGIN_REQUEST);//第二个参数用于区分不同的request
                currentPosition = position;
            }
        });
    }


    @Override
    /**
     * 接收返回的响应数据,并且刷新界面
     * 回调方法一般是自动执行的
     * requestCode:跳转时的请求码
     * resultCode:返回响应的结果码
     * data:返回响应的Intent对象
     */
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //
        super.onActivityResult(requestCode, resultCode, data);

        //保证如果是多个请求的话,区分不同页面的返回
        if (requestCode == LOGIN_REQUEST && resultCode == 200){
            //获得从NewActivity响应的数据
            String name = data.getStringExtra("name");
            //修改数据源
            names[currentPosition]=name;
            //刷新ListView
            adapter.notifyDataSetChanged();
        }
    }
}

NewActivity.java

package com.example.ch0401activity.activity;

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

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.ch0401activity.R;
import com.example.ch0401activity.Student;

public class NewActivity extends AppCompatActivity {

    private EditText etName;//不可以在这里调用findViewById方法,
                            //因为还没有加载布局文件,获取的会是空值
    private int position;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载新创建的布局文件
        setContentView(R.layout.activity_new);
        //接收从MainActivity传递的数据
        Intent request = getIntent();//获得的是启动的时候传入的intent对象

        //第一种 获取不适用Bundle封装的数据
        String name = request.getStringExtra("name");
        String phone = request.getStringExtra("phone");
        String email = request.getStringExtra("email");
        position = request.getIntExtra("position",0);//如果没有,就设置为默认值


        //第二种 借助Bundle
//        Bundle bundle = request.getBundleExtra("bundle");
//        //获取使用Bundle封装的数据
//        String name = bundle.getString("name");
//        String phone = bundle.getString("phone");
//        String email = bundle.getString("email");

        //第三种,获取自定义类型的数据
//        Student student = (Student) request.getSerializableExtra("stu");
//        String name = student.getName();
//        String phone = student.getPhone();
//        String email = student.getEmail();


        etName = findViewById(R.id.et_name);
        EditText etPhone = findViewById(R.id.et_phone);
        EditText etEmail = findViewById(R.id.et_email);
        //显示数据
        etName.setText(name);
        etPhone.setText(phone);
        etEmail.setText(email);

    }

    public void buttonOnClicked(View view) {
        //返回数据
        Intent response = new Intent();
        response.putExtra("name",etName.getText().toString());
        //响应的方法
        setResult(200,response);
        //结束当前的NewActivity
        finish();//会返回到MainActivity

    }
}

activity_main.xml

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

activity_new.xml

//xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="新的Activity"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名"
            android:textSize="25sp"/>
        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电话"
            android:textSize="25sp"/>
        <EditText
            android:id="@+id/et_phone"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="邮箱"
            android:textSize="25sp"/>
        <EditText
            android:id="@+id/et_email"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="buttonOnClicked"
        android:text="保存"/>

</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值