【Android开发】不同Activity之间的数据回传实例(一)摘桃子游戏

一、功能介绍

该项目实现的功能主要有:

  1. 在首页显示一个按钮点击该按钮跳转到桃园页面
  2. 在桃园页面,点击桃子会弹窗显示摘到几个桃子,同时被点击桃子消失,总桃子数+1
  3. 点击退出桃园会返回首页,首页桃子数会根据点击的桃子数动态增加

二、代码实现

1. 资源准备

将项目所需要的图片bg.png、monkey.png、btn_peach.png、peach_pic.png 导入程序的drawablehdpi文件夹中(默认情况下程序中没有drawable-hdpi 文件夹,需手动在res 文件夹中创建一个)。

2. 布局文件设计

2.1 主Activity

在layout文件夹中编辑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"><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:background="#008577"android:gravity="center"android:text="首页"android:textColor="@android:color/white"android:textSize="20sp" /><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/bg"android:gravity="center_vertical"><ImageViewandroid:id="@+id/iv_monkey"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/monkey" /><Buttonandroid:id="@+id/btn_peach"android:layout_width="80dp"android:layout_height="40dp"android:layout_marginLeft="30dp"android:layout_marginTop="250dp"android:layout_toRightOf="@id/iv_monkey"android:background="@drawable/btn_peach"android:gravity="center"android:text="去桃园"android:textColor="@android:color/black"android:textSize="18sp" /><ImageViewandroid:id="@+id/iv_peach"android:layout_width="45dp"android:layout_height="35dp"android:layout_below="@+id/btn_peach"android:layout_centerHorizontal="true"android:layout_marginTop="20dp"android:src="@drawable/peach_pic" /><TextViewandroid:id="@+id/tv_count"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/btn_peach"android:layout_marginTop="25dp"android:layout_marginLeft="10dp"android:layout_toRightOf="@id/iv_peach"android:text="摘到0 个"android:textColor="@android:color/black"android:textSize="20sp" /></RelativeLayout>
</LinearLayout>
2.2 辅Activity

在layout文件夹中新增activity_peach.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"><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:background="#008577"android:gravity="center"android:text="桃园"android:textColor="@android:color/white"android:textSize="20sp" /><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/tree_bg"><RelativeLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:layout_marginTop="70dp"android:background="@drawable/tree"><Buttonandroid:id="@+id/btn_one"android:layout_width="55dp"android:layout_height="40dp"android:layout_marginLeft="140dp"android:layout_marginTop="35dp"android:background="@drawable/peach_pic" /><Buttonandroid:id="@+id/btn_two"android:layout_width="55dp"android:layout_height="40dp"android:layout_below="@id/btn_one"android:layout_marginLeft="80dp"android:layout_marginTop="5dp"android:background="@drawable/peach_pic" /><Buttonandroid:id="@+id/btn_three"android:layout_width="55dp"android:layout_height="40dp"android:layout_below="@id/btn_one"android:layout_marginLeft="70dp"android:layout_marginTop="5dp"android:layout_toRightOf="@id/btn_two"android:background="@drawable/peach_pic" /><Buttonandroid:id="@+id/btn_four"android:layout_width="55dp"android:layout_height="40dp"android:layout_below="@id/btn_two"android:layout_marginLeft="25dp"android:layout_marginTop="15dp"android:background="@drawable/peach_pic" /><Buttonandroid:id="@+id/btn_five"android:layout_width="55dp"android:layout_height="40dp"android:layout_below="@id/btn_two"android:layout_marginLeft="70dp"android:layout_marginTop="15dp"android:layout_toRightOf="@id/btn_four"android:background="@drawable/peach_pic" /><Buttonandroid:id="@+id/btn_six"android:layout_width="55dp"android:layout_height="40dp"android:layout_below="@id/btn_two"android:layout_marginLeft="45dp"android:layout_marginTop="15dp"android:layout_toRightOf="@id/btn_five"android:background="@drawable/peach_pic" /></RelativeLayout><Buttonandroid:id="@+id/btn_exit"android:layout_width="100dp"android:layout_height="40dp"android:layout_alignParentRight="true"android:layout_alignParentBottom="true"android:layout_margin="50dp"android:background="@drawable/btn_peach"android:text="退出桃园"android:gravity="center"android:textColor="@android:color/black"android:textSize="18sp"/></RelativeLayout>
</LinearLayout>
2.3 其他资源文件

主题文件themes.xml

<resources xmlns:tools="http://schemas.android.com/tools"><!-- Base application theme. --><style name="Theme.PickPeach" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge"><!-- Primary brand color. --><item name="colorPrimary">@color/colorPrimary</item><item name="colorPrimaryVariant">@color/colorPrimaryDark</item><item name="colorOnPrimary">@color/white</item><!-- Secondary brand color. --><item name="colorSecondary">@color/teal_200</item><item name="colorSecondaryVariant">@color/teal_700</item><item name="colorOnSecondary">@color/black</item><!-- Status bar color. --><item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item><!-- Customize your theme here. --></style><style name="MyCustomTheme" parent="Theme.AppCompat.Light.NoActionBar"><!-- Primary brand color. --><item name="colorPrimary">@color/colorPrimary</item><item name="colorPrimaryVariant">@color/colorPrimaryDark</item><item name="colorOnPrimary">@color/white</item><!-- Secondary brand color. --><item name="colorSecondary">@color/teal_200</item><item name="colorSecondaryVariant">@color/teal_700</item><item name="colorOnSecondary">@color/black</item><!-- Status bar color. --><item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item><!-- Customize your theme here. --></style>
</resources>

3. 实现逻辑功能

3.0 全局配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.hzj.pickpeach"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/MyCustomTheme"><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activityandroid:name=".PeachActivity"android:exported="true"></activity></application></manifest>
3.1 首页功能

在MainActivity 中实现“去桃园”按钮的点击事件,当点击按钮时程序跳转到桃园摘桃的界面。同时,还需要接收桃园界面回传过来的桃子个数。

public class MainActivity extends AppCompatActivity {private Button btn_peach;private TextView tv_count;private int totalCount = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}private void init() {btn_peach = findViewById(R.id.btn_peach);tv_count = findViewById(R.id.tv_count);//为按钮设置点击事件监听器btn_peach.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//设置意图对象,实现界面跳转Intent intent = new Intent(MainActivity.this, PeachActivity.class);startActivityForResult(intent, 1);
//                startActivity(intent);}});}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);//判断请求码和返回码是否正确if (requestCode==1 && requestCode==1) {//获取回传的数据int count = data.getIntExtra("count", 0);;totalCount = totalCount + count;tv_count.setText("摘到" + totalCount + "个");}}
}
3.2 桃园界面的摘桃效果

点击桃子实现摘桃效果,同时全局桃子数动态变化,点击退出桃园,返回首页,同时更新首页桃子数。

public class PeachActivity extends AppCompatActivity implements View.OnClickListener {private Button btn_one, btn_two, btn_three, btn_four, btn_five, btn_six, btn_exit;private int count = 0;//桃子个数@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_peach);init();}private void init() {btn_one = findViewById(R.id.btn_one);btn_two = findViewById(R.id.btn_two);btn_three = findViewById(R.id.btn_three);btn_four = findViewById(R.id.btn_four);btn_five = findViewById(R.id.btn_five);btn_six = findViewById(R.id.btn_six);btn_exit = findViewById(R.id.btn_exit);btn_one.setOnClickListener(this);btn_two.setOnClickListener(this);btn_three.setOnClickListener(this);btn_four.setOnClickListener(this);btn_five.setOnClickListener(this);btn_six.setOnClickListener(this);btn_exit.setOnClickListener(this);}@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.btn_one: //第一个桃子的点击事件info(btn_one);break;case R.id.btn_two: //第二个桃子的点击事件info(btn_two);break;case R.id.btn_three: //第三个桃子的点击事件info(btn_three);break;case R.id.btn_four: //第四个桃子的点击事件info(btn_four);break;case R.id.btn_five: //第五个桃子的点击事件info(btn_five);break;case R.id.btn_six: //第六个桃子的点击事件info(btn_six);break;case R.id.btn_exit: //“退出桃园”按钮的点击事件returnData();break;default:throw new IllegalStateException("Unexpected value: " + view.getId());}}/*** 按钮的点击事件处理*/private void info(Button btn) {//桃子个数加1count++;//被摘掉的桃子设置为隐藏不可见btn.setVisibility(View.INVISIBLE);Toast.makeText(PeachActivity.this, "摘到" + count + "个桃子",Toast.LENGTH_LONG).show();}/*** 将数据回传到上个界面*/private void returnData() {//设置意图对象,将摘桃子的个数回传给首页界面Intent intent = new Intent();intent.putExtra("count", count);//返回码标识setResult(1, intent);//销毁本界面PeachActivity.this.finish();}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {//当点击设备返回键时,调用数据回传方法,返回首页界面if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {returnData();}return false;}
}

三、效果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/614913.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构与算法教程,数据结构C语言版教程!(第三部分、栈(Stack)和队列(Queue)详解)四

第三部分、栈(Stack)和队列(Queue)详解 栈和队列&#xff0c;严格意义上来说&#xff0c;也属于线性表&#xff0c;因为它们也都用于存储逻辑关系为 "一对一" 的数据&#xff0c;但由于它们比较特殊&#xff0c;因此将其单独作为一章&#xff0c;做重点讲解。 使用栈…

1.UnityProfiler性能分析提升性能

一 Stats重要参数详解 1.main thread 主线程 业务逻辑都在这里&#xff0c;我们调用Unity API都在这里&#xff1b;例如设置transform位置&#xff0c;main thread里面处理 2.render thread&#xff0c;渲染线程&#xff0c;负责渲染图像、执行渲染循环、处理GPU命令、帧同步。…

zabbix和prometheus怎么选?

简单粗暴的回答&#xff0c;不搞弯弯绕&#xff01; zabbix和prometheus对比 发行时间开发语言性能社区支持容器支持企业使用部署难度Prometheus2016go支持万为单位相对不如zabbix&#xff0c;人数与日俱增。不仅支持swarm原生集群,还支持Kubernetes容器集群&#xff0c;是目前…

MATLAB mat 文件

1.mat文件格式 MATLAB&#xff08;Matrix Laboratory&#xff09;使用 .mat 文件格式来存储和加载数据。MAT 文件是一种二进制文件格式&#xff0c;能够保存 MATLAB 中的各种数据类型&#xff0c;包括矩阵、向量、结构体、元胞数组等。 特定和用途&#xff1a; 二进制格式&a…

计算机网络系统结构-2020期末考试解析

【前言】 不知道为什么计算机网络一门课这么多兄弟&#xff0c;这份看着也像我们的学科&#xff0c;所以也做了。 一&#xff0e; 单选题&#xff08;每题 2 分&#xff0c;共 20 题&#xff0c;合计 40 分&#xff09; 1 、当数据由主机 A 发送到主机 B &#xff0c;不参…

机器学习_7、KNN

数据采用&#xff1a;电离层数据 KNN完整的代码电离层数据资源-CSDN文库 代码 import os import csv import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import …

ChatGPT可以帮你做什么?

学习 利用ChatGPT学习有很多&#xff0c;比如&#xff1a;语言学习、编程学习、论文学习拆解、推荐学习资源等&#xff0c;使用方法大同小异&#xff0c;这里以语言学习为例。 在开始前先给GPT充分的信息&#xff1a;&#xff08;举例&#xff09; 【角色】充当一名有丰富经验…

【分布式微服务专题】从单体到分布式(四、SpringCloud整合Sentinel)

目录 前言阅读对象阅读导航前置知识一、什么是服务雪崩1.1 基本介绍1.2 解决方案 二、什么是Sentinel2.1 基本介绍2.2 设计目的2.3 基本概念 三、Sentinel 功能和设计理念3.1 流量控制3.2 熔断降级3.3 系统负载保护 四、Sentinel 是如何工作的 笔记正文一、简单整合Sentinel1.1…

sqlalchemy 事务自动控制(类java aop)

最近使用它交互数据库&#xff0c;想实现类似java aop那种自动事务控制&#xff0c;不用手动commit或者rollback。我是用的是flaskdenpendency-injecter 这是我的db的配置类&#xff0c;里面会初始化一些session配置&#xff0c;里面比较重要的是把autocommit和autoflush关闭了…

Zynq 电源

ZYNQ芯片的电源分PS系统部分和PL逻辑部分&#xff0c;两部分的电源分别是独立工作。PS系统部分的电源和PL逻辑部分的电源都有上电顺序&#xff0c;不正常的上电顺序可能会导致ARM系统和FPGA系统无法正常工作。 PS部分的电源有VCCPINT、VCCPAUX、VCCPLL和PS VCCO。 VCCPINT为PS内…

通过CSS实现渐变色边框

通过CSS实现渐变色边框的几种方法&#xff1a; 1. 使用border-image实现渐变色边框&#xff0c;边框圆角 .box{border-radius: 16px;border: 10px solid;border-image: linear-gradient(#8f41e9, #578aef,#ff5277)30 30;}这种方式虽然简单但有个明显的缺陷&#xff0c;不支持…

便捷好用的iOS文件管理App

便捷好用的iOS文件管理App 摘要 本文介绍了一款功能强大、免费的iOS文件管理App——克魔助手。通过使用克魔助手&#xff0c;用户可以轻松管理手机存储空间&#xff0c;清理垃圾文件&#xff0c;整理文件&#xff0c;并进行文件传输和截图操作。本文将详细介绍克魔助手的各项…

学习使用php、js脚本关闭当前页面窗口的方法

学习使用php、js脚本关闭当前页面窗口的方法 前言方法一&#xff1a;使用JavaScript代码方法二&#xff1a;通过http头文件来实现方法三&#xff1a;使用服务器端脚本来实现 前言 在开发web应用程序时&#xff0c;我们通常需要在不同的网页之间进行导航。通常情况下&#xff0…

使用Sqoop将数据导入Hadoop的详细教程

在大数据处理中&#xff0c;Sqoop是一个强大的工具&#xff0c;它可以将关系型数据库中的数据导入到Hadoop生态系统中&#xff0c;以便进行进一步的分析和处理。本文将提供一个详细的教程&#xff0c;以帮助大家了解如何使用Sqoop将数据导入Hadoop。 准备工作 在开始之前&…

Could not erase files or folders:

IDEA删除 git 的 localChanges 内的文件时&#xff0c;提示Could not erase files or folders:。 确认下这个文件是否被打开&#xff0c;忘记关闭了&#xff1b;关闭后可以被删除。&#xff08;文件被打开的情况下&#xff0c;用操作系统自带的删除&#xff0c;也无法删除成功…

代码随想录 Leetcode707. 设计链表

题目&#xff1a; 代码(首刷看解析 2024年1月11日&#xff09;&#xff1a; class MyLinkedList { private:struct ListNode{int val;ListNode* next;ListNode(int val):val(val),next(nullptr){}};int size;ListNode* dummyHead; public:MyLinkedList() {dummyHead new List…

[centos]centos6更换源的正确方法

已经2024年了&#xff0c;自从2020年11月30日开始 centos6各大开源镜像站已经停止维护了&#xff0c;所以导致yum的repo源不能正常使用&#xff0c;阿里云的repo库目前还可以使用&#xff0c;可以把repo源切换到阿里云暂时满足使用需求。不过这个也很难说以后不会失效&#xff…

【Pytorch简介】2.What are Tensors 什么是张量?

2.What are Tensors 什么是张量&#xff1f; 文章目录 2.What are Tensors 什么是张量&#xff1f;Initializing a Tensor 初始化张量Directly from data 直接来自数据From a NumPy array 来自 NumPy 数组From another tensor 从另一个张量With random or constant values 使用…

【算法】增减序列(贪心,差分)

题目 给定一个长度为 n 的数列 a1,a2,…,an&#xff0c;每次可以选择一个区间 [l,r]&#xff0c;使下标在这个区间内的数都加一或者都减一。 求至少需要多少次操作才能使数列中的所有数都一样&#xff0c;并求出在保证最少次数的前提下&#xff0c;最终得到的数列可能有多少种…

机器人制作开源方案 | 六足灾后探测机器人

作者&#xff1a;毕钟诚 施钥 范江龙 张莉曼 陈金凤 单位&#xff1a;中国石油大学&#xff08;北京&#xff09; 指导老师&#xff1a;许亚岚 孙琳 世纪全球自然灾害频发&#xff0c;灾后探测重建工作十分重要&#xff0c;极端恶劣的现场探测环境&#xff0c;频发的余震甚至…