<span role="heading" aria-level="2">Activity组件(四):通过requestCode和resultCode来实现Activity间的数据回传</span>

一、什么是数据回传

开发时,通过一个Activity来调用另一个Activity,当用户在第二个Activity中操作完成后,自动返回第一个Activity并将数据传给第一个Activity,从而使得第一个Activity可以获取第二个Activity的数据。

在第一个Activity界面中,通过startActivityForResult()来启动第二个Activity界面,在第二个界面中将数据通过setResult()回传,在第一个Activity中重写onActivityResult()方法。

requestCode:代表了启动Activity的请求码,用于标识请求来源,进而判断这个返回的数据的路径,从哪里开始,经过哪里,又回到这里。

resultCode:通过结果码在onActivityResult()方法进行判断,用来区分结果

二、实现充值的数据回传

点击按钮进入充值页面

 

 

 

 

直接点击确认充值,判断数据为空

 

 输入充值金额

 

 点击确认充值

 

 再次点击按钮进入充值界面

 

 点击取消充值

 

 AndroidManifest.xml

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

    <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=".PayActivity"/>
    </application>

</manifest>

activity_main.xml

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

    <Button
        android:id="@+id/recharge_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击进行充值" />
    <TextView
        android:id="@+id/pay_result"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>

</LinearLayout>

activity_pay.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:text="充值界面"
        android:textSize="30sp"
        android:layout_marginTop="40dp"
        android:layout_gravity="center"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/pay_input_box"
        android:layout_width="match_parent"
        android:layout_marginTop="30dp"
        android:hint="请输入充值金额"
        android:inputType="number"
        android:maxLines="1"
        android:layout_height="wrap_content"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_marginTop="20dp"
        android:layout_height="match_parent">
    <Button
        android:id="@+id/start_pay_btn"
        android:layout_width="wrap_content"
        android:layout_marginLeft="40dp"
        android:text="确认充值"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/cancel_pay_btn"
        android:layout_width="wrap_content"
        android:layout_marginRight="40dp"
        android:layout_alignParentRight="true"

        android:text="取消充值"
        android:layout_height="wrap_content"/>
    </RelativeLayout>
</LinearLayout>

MainActivity.java

package com.example.activityforresultdemo;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    private Button mRechargeBtn;
    private TextView mPayResult;
    private  static final int PAY_RESULT_CODE =1;

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

    private void initListener() {
        mRechargeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置点击事件
                Intent intent =new Intent(MainActivity.this,PayActivity.class);
                //使用startActivityForResult来替代原来的startActivity
                startActivityForResult(intent,PAY_RESULT_CODE);
            }
        });
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mRechargeBtn = (Button) this.findViewById(R.id.recharge_btn);
        mPayResult =(TextView) this.findViewById(R.id.pay_result);
    }

    /**
     * 返回的结果在这里回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String resultContent = null;
        //当我们判断这个请求码的时候,就知道,这是充值界面返回的结果
        if (requestCode==PAY_RESULT_CODE) {
            if(resultCode==2){
                //充值成功
                resultContent=data.getStringExtra("resultContent");
            }else if(resultCode==3){
                //充值被取消
                resultContent=data.getStringExtra("resultContent");
            }
            mPayResult.setText(resultContent);
        }
    }
}

PayActivity.java

package com.example.activityforresultdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class PayActivity extends Activity {

    private EditText mInoutBox;
    private Button mStartPayBtn;
    private Button mCancelPayBtn;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        initView();
        initListener();
    }

    private void initListener() {
        mStartPayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                handlerPay();
            }
        });
        mCancelPayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handlerCancel();
            }
        });
    }

    private void handlerCancel() {
        Intent intent =new Intent();
        intent.putExtra("resultContent","充值已被取消");
        setResult( 3,intent);
        finish();
    }

    private void handlerPay() {
        String paynumber=mInoutBox.getText().toString().trim();
        if (TextUtils.isEmpty(paynumber)) {
            Toast.makeText(PayActivity.this,"未输入充值金额",Toast.LENGTH_SHORT).show();
            return;
        }
        //充值成功
        //setResult()有两个重载方法,一个只有resultCode,另一个还有intent
        Intent intent =new Intent();
        intent.putExtra("resultContent","成功充值"+paynumber+"元");
        setResult(2,intent);
        finish();
    }

    private void initView() {
        mInoutBox=(EditText) this.findViewById(R.id.pay_input_box);
        mStartPayBtn=(Button) this.findViewById(R.id.start_pay_btn);
        mCancelPayBtn=(Button) this.findViewById(R.id.cancel_pay_btn);
    }


}

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
点赞 评论 收藏
分享
06-13 17:33
门头沟学院 Java
顺序不记了,大致顺序是这样的,有的相同知识点写分开了1.基本数据类型2.基本数据类型和包装类型的区别3.==和equals区别4.ArrayList与LinkedList区别5.hashmap底层原理,put操作时会发生什么6.说出几种树型数据结构7.B树和B+树区别8.jvm加载类机制9.线程池核心参数10.创建线程池的几种方式11.callable与runnable区别12.线程池怎么回收线程13.redis三剑客14.布隆过滤器原理,不要背八股,说说真正使用时遇到了问题没有(我说没有,不知道该怎么回答了)15.堆的内存结构16.自己在写项目时有没有遇见过oom,如何处理,不要背八股,根据真实经验,我说不会17.redis死锁怎么办,watchdog机制如何发现是否锁过期18.如何避免redis红锁19.一个表性别与年龄如何加索引20.自己的项目的QPS怎么测的,有没有真正遇到大数量表21.说一说泛型22.springboot自动装配原理23.springmvc与springboot区别24.aop使用过嘛?动态代理与静态代理区别25.spring循环依赖怎么解决26.你说用过es,es如何分片,怎么存的数据,1000万条数据怎么写入库中27.你说用limit,那么在数据量大之后,如何优化28.rabbitmq如何批次发送,批量读取,答了延迟队列和线程池,都不对29.计网知不知道smtp协议,不知道写了对不对,完全听懵了30.springcloud知道嘛?只是了解反问1.做什么的?短信服务,信息量能到千万级2.对我的建议,基础不错,但是不要只背八股,多去实际开发中理解。面试官人不错,虽然没露脸,但是中间会引导我回答问题,不会的也只是说对我要求没那么高。面完问我在济宁生活有没有困难,最快什么时候到,让人事给我聊薪资了。下午人事打电话,问我27届的会不会跑路,还在想办法如何使我不跑路,不想扣我薪资等。之后我再联系吧,还挺想去的😭,我真不跑路哥😢附一张河科大幽默大专图,科大就是大专罢了
查看30道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务