简体   繁体   English

从不同的活动中从TextView获取文本

[英]getting the text from a TextView from a different activiy

I have 2 activities: Activity_A and Activity_B. 我有2个活动:Activity_A和Activity_B。 On Activity_A I have a TextView with the id "MyTextView". 在Activity_A上,我有一个ID为“ MyTextView”的TextView。 How can I get its text from Avtivity_B? 如何从Avtivity_B获取其文本? I have tried to do this in Activity_B main Java file: 我试图在Activity_B主Java文件中执行此操作:

txtv = (TextView) findViewById(R.id.MyTextView);
txtv.getText().toString()

But this didn't work. 但这没有用。
Is there any way to this without Intents? 没有意图,有什么办法吗?

You should get the content on the Activity where you have it and then send data from activity A to activity B with the intent: 您应该在活动所在的位置获得内容,然后有意地将数据从活动A发送到活动B:

Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("fromActivityA",textView.getText());

And then you have to use getExtra() method on activity B for getting the data you send from activity A. 然后,您必须在活动B上使用getExtra()方法来获取从活动A发送的数据。

Hope you can find this helpful! 希望对您有所帮助!

The challenge is that when an activity is not visible, it has been paused, and is no longer available. 挑战在于,当某个活动不可见时,该活动将被暂停,并且不再可用。 Also the id used in findViewById may refer to an id in the other activities layout file. 此外,在findViewById中使用的ID可能引用其他活动布局文件中的ID。 Using an intent to pass the data when moving between activities is a good solution, or if you really need access to that data from different activities you could store it in shared preferences, in a database, or as a static field on the activity class itself. 在活动之间移动时使用意图传递数据是一个很好的解决方案,或者,如果您确实需要从其他活动访问该数据,则可以将其存储在共享首选项中,数据库中或活动类本身的静态字段中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM