Add view to already existing xml viewgroup in code Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Add view to already existing xml viewgroup in code without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I would like to be able to add a view to an already existing xml layout in code:

        LinearLayout ll = (LinearLayout) findViewById(R.layout.common_list);

        TextView tv = new TextView(this);
        tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        tv.setText("sample text");
        ll.addView(tv);

        setContentView(ll); 

When creating a new LinearLayout in code it works, but when using a Resource like in the code above it doesn’t.

common_list.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Quick List"/>

</LinearLayout>

Answer

Try to use LayoutInflater

LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.common_list)
TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setText("sample text");
ll.addView(tv);

setContentView(ll);

If this won’t work, please add error from Logcat.

Also, you should change properties from android:layout_width=”fill_parent” to android:layout_width=”wrap_content” in yout LinearLayout in common_list.xml and also do the same thing to your TextView in common_list.xml

Why? Because your layout is horizontal-oriented and it fills whole screen space. Your TextEdit fills as much space as your layout does (so in this case it’s whole screen space). Now, when you add another TextView it is adding properly – to right of your first TextEdit, so it’s like out of screen. To understand exactly what happens:

-----------------
||-------------||---------------
||| TextViev1 ||||addedTextView|
||-------------||---------------
||             ||
||             ||
||             ||
||             ||
||             ||
||LinearLayout ||
||-------------||
|    screen     |
----------------

I also had this problem many times. Usually if you add View to layout and you don’t see it (and you get no errors) problem is with width/heigth or position (ex. when you use RelativeLayout).

We are here to answer your question about Add view to already existing xml viewgroup in code - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji