简体   繁体   中英

How can I setText() (TextView) when the TextView is in another layout?

My app has 2 layouts (main layout) and (preference (prefs) layout).

When the MainActivity loads, I set setContentView(R.layout.main); - main layout

I need to then set text for a TextView in the preference layout, but it never gets set.

LayoutInflater factory = getLayoutInflater();
 View inflate = factory.inflate(R.layout.prefs, null);
    TextView eSerial = (TextView) inflate.findViewById(R.id.editTextSerial);
    mSerial = "Test"; 
    eSerial.setText(mSerial);

The way I get to the preference page is with a menu and then the page loads up with no change to TextView

I have searched and not found an answer yet.

Please help.

Thank you.

Short answer: You can't do this.

Long answer:

If you are launching the preference page yourself, you must be creating an Intent to do so. Call putExtra() to store your text inside that intent. In your PreferenceActivity, call getIntent().getStringExtra() to get the text, then put it in your TextView.

When the menu kicks off your prefs activity, you can populate the view with the values. user1853479 points out one way of doing this, which is to add the values to an intent. Assuming you want to store these prefs for future runs, you can also set any that for that specific run and save them in your local store. Another method is to create a singleton to store your settings, load it when your app starts, modify and save as needed, and access it from any of your activities.

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