如何将字符串从一个活动发送到另一个活动? [英] How to send string from one activity to another?

查看:36
本文介绍了如何将字符串从一个活动发送到另一个活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在activity2中有一个字符串

I have a string in activity2

String message = String.format(
"Current Location 
 Longitude: %1$s 
 Latitude: %2$s", lat, lng); 

我想将此字符串插入到活动 1 的文本字段中.我该怎么做?

I want to insert this string into text field in activity1. How can I do that?

推荐答案

您可以使用意图,这是在活动之间发送的消息.在 Intent 中,您可以放置​​各种数据,String、int 等.

You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.

在您的情况下,在 activity2 中,在转到 activity1 之前,您将以这种方式存储字符串消息:

In your case, in activity2, before going to activity1, you will store a String message this way :

Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);

activity1中,在onCreate()中,您可以通过检索Bundle来获取String消息(其中包含调用活动发送的所有消息)并在其上调用 getString() :

In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :

Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");

然后就可以在TextView中设置文字:

Then you can set the text in the TextView:

TextView txtView = (TextView) findViewById(R.id.your_resource_textview);    
txtView.setText(message);

希望这有帮助!

这篇关于如何将字符串从一个活动发送到另一个活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆