Android之路——第二步:Activity之间传值(Intent、onActivityResult)

我的博客:http://blog.csdn.net/name_cjf

前言

上一篇博客中我们了解了如何切换Activity,然而一个真实的app中,不仅需要可以切换Activity,还需要使Activity之间可以通信。所以今天就讲讲Activity的传值。

传值方法简介

关于Activity传值,其实是很灵活的,其中大概有以下几类传值方法:

  1. Intent传值:这是Android中最普通的传值方式,Intent作为切换Activity时候使用的纽带,可以携带数据,但不宜过大。(Intent可以绑定一个Bundle来传值,这个方法暂且不讲,有兴趣的同学自己去百度)
  2. 全局变量传值:该方法其实在Java中也很常见,设置一个全局变量,多个Activity可以共同给他赋值。这种方法的好处是传值的大小不限。
  3. EventBus等黑科技:为了方便开发,现在出现了许许多多的新的方法,都是比较方便实用的,不过这类型的方法最好在基础知识比较扎实的时候再去研究

Activity传值

布局文件:
activity_main.xml

<?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/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="你好,世界1" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="切换到另一个activity"/>

</LinearLayout>

activity_second.xml

<?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/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="你好,世界2" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="切换回第一个activity"/>

</LinearLayout>

代码:
MainActivity.java

package com.study.cjf.activitychangewithvalue;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView text1;
    private Button btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text1 = findViewById(R.id.text1);
        btn1 = findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //第一个参数是要向世界2传值的名称,第二个参数是所传的值。值可以是很多种类型,也可以是序列化的对象,这里不展开叙述
                intent.putExtra("welcome", "你好,我是世界2,这是从世界1传来的消息");
                intent.setClass(MainActivity.this, SecondActivity.class);
                //startActivity(intent);普通切换Activity所用方法
                startActivityForResult(intent, 1);//该方法在切换Activity的同时,会接收所打开的Activity关闭时返回回来的值。
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {//目标Activity关闭后,该方法会自动执行(回调)
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {//这里的1就是startActivityForResult调用时所传的值。如果当时传了2,则对应Activity关闭后,返回的就是2111
            if (data != null) {
                String str = data.getStringExtra("welcome2");//获取传回的字符
                text1.setText(str);//给TextView设置传来的文字
            }
        }
    }
}

SecondActivity.java

package com.study.cjf.activitychangewithvalue;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Machenike on 2017/10/8.
 */

public class SecondActivity extends Activity {

    private TextView text2;
    Button btn2;

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

        Intent intent = getIntent();//获取打开这个Activity时所用的Intent
        String str = intent.getStringExtra("welcome");//获取传来的值

        text2 = findViewById(R.id.text2);
        text2.setText(str);//设置TextView的文字
        btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("welcome2", "我来自世界2,我改变了世界1的文字");
                setResult(1, intent);//没有设置的话,世界1(MainActivity)中onActivityResult回调的第三个参数为null,但仍然会回调
                finish();
            }
        });
    }
}

最后别忘了在Mainfest.xml中配置两个Activity

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.study.cjf.activitychangewithvalue">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"/>
    </application>

</manifest>

效果

打开app
打开app
点击按钮切换Activity并传值:
点击按钮切换Activity并传值
点击按钮关闭Activity并回调传值:
点击按钮关闭Activity并回调传值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值