Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child views programmatically from a layout [from a R.layout resource]

At some point in my app in need to get views (actually, it should be one) from a layout. What I know about the layout is it's int reference, in the form of R.layout.my_layout.

How can I get the views inside?

I tried getting the root view with

View rootView = (View) getResources().getLayout(R.layout.my_layout)

but obviously it didn't work. getLayout() returns a XMLResourceParser object, which I don't know how to manage.

I can't work with IDs.

like image 997
natario Avatar asked Dec 14 '25 07:12

natario


2 Answers

Use layout inflater

View rootView = View.inflate(context, R.layout.my_layout, null);
like image 138
SorryForMyEnglish Avatar answered Dec 16 '25 22:12

SorryForMyEnglish


To load the view:

    LayoutInflater inflater = LayoutInflater.from(getContext());
    View v = inflater.inflate(R.layout.your_layout, null);

And to get sub views from it:

    View sub = v.findViewById(R.id.your_sub_view_id);
like image 20
Corbella Avatar answered Dec 16 '25 22:12

Corbella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!