1

I'm going to create a new RelativeLayout with some Text and Image Views programatically and then add it to a parent layout. The question: is it possible to define that layout in XML and then just add it to the parent programatically? Would be a faster way..

3 Answers 3

4

Use inflation:

final LayoutInflater lyInflaterForPanel = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout lLayoutPanel = (LinearLayout) lyInflaterForPanel.inflate(
                R.layout.my_row, null);

This has worked for me.

Sign up to request clarification or add additional context in comments.

3 Comments

thx, it works. BUT, the layout that I did inflate has some TextViews. I initialized them after inflating the layout and tried to set the text, but it causes crashes. Any ideas how to fix that?
I think it should work. Can you post logcat with your updated code?
it gives me a "Delivery Failure" error since I tried so set the text in the OnActivityResult() method (caused by NullPointerException). I did initialize the TextView after inflating its parent layout, but any action other then initialization (findViewById) causes a NullPointerException..
1

Yes, using LayoutInflater you will inflate your XML then add it to the parent..

check, What does LayoutInflater in Android do?

Comments

0

Use LayoutInflater class for that. It will covert your layout into a view and add it to parent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.