Android手把手编写儿童手机远程监控App之四大组件详解2

0 阅读4分钟

概述

上节Android手把手编写儿童手机远程监控App之四大组件详解 讲到Activity常用控件以及Activity生命周期函数。这节继续说明Activity剩下内容。

Activity传参

在 Android 开发中,Activity 之间的传参是非常常见的操作,是从一个Activity(界面)向另一个Activity传递数据的过程。主要有以下几种方式,我会从最简单到最复杂进行介绍。

  • 传递基本数据类型
  • 传递Bundle对象(适合传递大量数据)
  • 通过Serializable传递对象数据 在这里插入图片描述

目前嘟宝,共有两个Activity页面,分别是:HelloWorldActivity、MainActivity,默认HelloWorldActivity是启动页面,将MainActivity设置为启动页面,并将两页内容恢复初始状态。 将MainActivity设置为启动页面,在AndroidManifest修改,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.zilong.dubao">
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@drawable/fav"
        android:label="@string/app_name"
        android:roundIcon="@drawable/favround"
        android:supportsRtl="true"
        android:theme="@style/Theme.DuBao"
        tools:targetApi="31">
        <activity
            android:name=".HelloWorldActivity"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Activity传参传递基本数据

基本数据如字符串、数字、浮点型数据,但对于素组、对象则无法传递。但对于实际开发中,应用较多,属于必掌握内容。

  • MainActivity创建一个按钮,单击启动HelloWorldActivity,传递数据
  • HelloWorldActivity启动后接收数据,并将数据显示 核心代码 传参
  Intent intent = new Intent(MainActivity.this, HelloWorldActivity.class);
  intent.putExtra("fish_name", "鲫鱼");
  intent.putExtra("fish_num", 125);
  intent.putExtra("fish_price", 19.5);
  startActivity(intent);

接收参数

   Intent intent=getIntent();
   String fish_name=intent.getStringExtra("fish_name");
   int fish_num=intent.getIntExtra("fish_num",0);
   double fish_price=intent.getDoubleExtra("fish_price",0.0);

MainActivity代码及其资源样式代码

package com.zilong.dubao;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=findViewById(R.id.start);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HelloWorldActivity.class);
                intent.putExtra("fish_name", "鲫鱼");
                intent.putExtra("fish_num", 125);
                intent.putExtra("fish_price", 19.5);
                startActivity(intent);

            }
        });
    }
}
<?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:gravity="center_vertical"
    android:orientation="vertical">
<Button
    android:id="@+id/start"
    android:text="启动"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

HelloWorldActivity代码及其资源样式代码

package com.zilong.dubao;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HelloWorldActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_world);
        Intent intent=getIntent();
        String fish_name=intent.getStringExtra("fish_name");
        int fish_num=intent.getIntExtra("fish_num",0);
        double fish_price=intent.getDoubleExtra("fish_price",0.0);
        TextView textViewName=findViewById(R.id.fish_name);
        textViewName.setText("名称:"+(fish_name==null?"未知":fish_name));
        TextView textViewNum=findViewById(R.id.fish_num);
        textViewNum.setText("数量:"+fish_num);
        TextView textViewPrice=findViewById(R.id.fish_price);
        textViewPrice.setText("价格:"+fish_price);
    }
}
<?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:id="@+id/fish_name"
        android:layout_width="match_parent"
        android:textSize="26dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/fish_num"
        android:layout_width="match_parent"
        android:textSize="26dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/fish_price"
        android:layout_width="match_parent"
        android:textSize="26dp"
        android:layout_height="wrap_content"/>
</LinearLayout>

运行效果 在这里插入图片描述 其中,在MainActivity布局中,加入 android:gravity="center_vertical"是控件垂直居中。在接收数据时,对字符串做非空校验 textViewName.setText("名称:"+(fish_name==null?"未知":fish_name));

Activity 传参Bundle对象(适合传递大量数据)

Activity 传递参数,对于String、int基本类型数据,可以使用intent.putExtra。但对于数组则无能为例。Bundle不仅能够传递基本类型数据,对于数组参数的支持,使得传递参数很方便。 基本用法:

  • 传参
 Intent intent = new Intent(MainActivity.this, HelloWorldActivity.class);
 Bundle bundle=new Bundle();
 bundle.putStringArray("fish",new String[]{"鲫鱼","草鱼","鲤鱼"});
  bundle.putInt("fish_num",111);
  bundle.putDouble("fish_price",9.9);
  intent.putExtras(bundle);
  startActivity(intent);
  • 接收参数
 Intent intent=getIntent();
  Bundle bundle = intent.getExtras();
  if (bundle == null) {
       return;
   }
   String[] fishs = bundle.getStringArray("fish");
   int fish_num = bundle.getInt("fish_num");
   double fish_price=bundle.getDouble("fish_price");

具体MainActivity代码,资源样式为改变:

package com.zilong.dubao;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=findViewById(R.id.start);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HelloWorldActivity.class);
                Bundle bundle=new Bundle();
                bundle.putStringArray("fish",new String[]{"鲫鱼","草鱼","鲤鱼"});
                bundle.putInt("fish_num",111);
                bundle.putDouble("fish_price",9.9);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
    }
}

HelloWorldActivity代码资源样式为改变

package com.zilong.dubao;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HelloWorldActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_world);

        Intent intent=getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            return;
        }
        String[] fishs = bundle.getStringArray("fish");
        int fish_num = bundle.getInt("fish_num");
        double fish_price=bundle.getDouble("fish_price");
        String fish_name="";
        for (int i = 0; i < fishs.length; i++) {
            fish_name+=fishs[i];
        }
        TextView textViewName=findViewById(R.id.fish_name);
        textViewName.setText("名称:"+(fish_name==null?"未知":fish_name));
        TextView textViewNum=findViewById(R.id.fish_num);
        textViewNum.setText("数量:"+fish_num);
        TextView textViewPrice=findViewById(R.id.fish_price);
        textViewPrice.setText("价格:"+fish_price);
    }
}

运行效果 在这里插入图片描述

通过Serializable传递对象数据

Bundle不仅可以传递基本类型数据,数组数据,但对于用户自定义数据则无能为例。如下结构

public class Fish {
    String name;
    int num;
    double price;
    Fish(String name,int num,double price){
        this.name=name;
        this.num=num;
        this.price=price;

    }
}

Bundle则无法传递,但可以通过Serializable传递。

  • 首先定义Fish类,继承Serializable接口
  • 在MainActivity中,intent.putExtra 传递Fish类型数据
  • HelloWorldActivity通过getSerializableExtra接收Fish类型数据 Fish代码
package com.zilong.dubao;

import java.io.Serializable;

public class Fish implements Serializable {
    String name;
    int num;
    double price;
    Fish(String name,int num,double price){
        this.name=name;
        this.num=num;
        this.price=price;

    }
}

MainActivity代码

package com.zilong.dubao;

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.start);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HelloWorldActivity.class);
                Fish fish=new Fish("鲫鱼",24,9.9);
                intent.putExtra("fish",fish);
                startActivity(intent);

            }
        });
    }
}

HelloWorldActivity代码

package com.zilong.dubao;
import androidx.appcompat.app.AppCompatActivity;

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

public class HelloWorldActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_world);
        Intent intent=getIntent();
        Fish fish=(Fish) intent.getSerializableExtra("fish");
        TextView textViewName=findViewById(R.id.fish_name);
        textViewName.setText("名称:"+fish.name);
        TextView textViewNum=findViewById(R.id.fish_num);
        textViewNum.setText("数量:"+fish.num);
        TextView textViewPrice=findViewById(R.id.fish_price);
        textViewPrice.setText("价格:"+fish.price);
    }
}

运行效果 在这里插入图片描述