如何将字符串从一个活动发送到另一个活动?
我在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);
希望这有帮助!