简体   繁体   中英

Android a string in multiple Activities?

I want to know how to make a string that can be used in multiple .java files(activities).

What I'm going. I'm getting a string equal to what is in a .txt file and I want to take bits from that and use them for TextViews text in the activity. Then use other bits in a different activity in a TextView...

I'm thinking making the .txt file into a string that is viewable by all activities will be the best way of doing this. All help is appreciated.

If I am getting this right, you probably need a static String variable added to one of your classes (or create brand new class for this) and populated with value from text file.

It can be then accessed by other classes using [ClassName].[variableName].

You can also make it private and add appropriate static get/set methods.

EDIT:

The simplest way is probably to declare a class variable in MainActivity as below

public static String testString;

You neeed to populate that variable with the value you want. To do this you can call:

testString = "example"; //from within MainActivity class

or

MainActivity.testString = "example"; //from any other class

To get the value of the variable in a different class, you just call

String value = MainActivity.testString;

You will need MainActivity added to imports in every class you call it.

Once yo get your head around this, it might be better to create a seperate class holding this variable (and any others you need) and create private variable instead with getter/setter methods.

Hope that clarifies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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