user2519193
user2519193

Reputation: 211

In Android, how to I edit views in a layout, when my setContentView is not in that layout?

For example, I might be in R.Layout.activity_main ,

but when I onCreate my activity, I want to change a TextView in another layout, so I would create a TextView object and findViewById from that layout, and then change it.

But this will not work unless I set my contentview to that layout, but is it possible to be able to set the TextView in that layout, without having to setContentView to that layout?

Upvotes: 0

Views: 132

Answers (2)

hasanghaforian
hasanghaforian

Reputation: 14022

It is better to store a reference of desired view in a class as a variable when you create it's parent layout.Then change it's property when you need.

You can see more details in these two questions:

Android: How to declare global variables?

Android, how to access Activity UI from my class?

Upvotes: 0

Brian
Brian

Reputation: 8085

This does not work in all situations, but you could try a LayoutInflator.

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.your_layout, null);

Then to find views in that layout, just do...

layout.findViewById(R.id.your_view);

Upvotes: 1

Related Questions