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..

Droidman
  • 11,485
  • 17
  • 93
  • 141

3 Answers3

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.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
  • 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? – Droidman Nov 07 '12 at 12:42
  • I think it should work. Can you post logcat with your updated code? – MysticMagicϡ Nov 07 '12 at 13:20
  • 1
    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.. – Droidman Nov 07 '12 at 13:53
1

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

check, What does LayoutInflater in Android do?

Community
  • 1
  • 1
Nermeen
  • 15,883
  • 5
  • 59
  • 72
0

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

Guna
  • 121
  • 8