Add a view to an existing xml viewer in code

I would like to be able to add a view to an 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, as in the code above, it does not.

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> 
+4
source share
1 answer

Try using 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 does not work, add an error to Logcat.

You should also change the properties of android: layout_width = "fill_parent" to android: layout_width = "wrap_content" in yout LinearLayout in common_list.xml, and also do the same with your TextView in common_list.xml

Why? Since your layout is horizontally oriented and fills the entire screen space. Your TextEdit fills as much space as your layout does (so in this case it is all screen space). Now, when you add another TextView, it adds correctly - to the right of your first TextEdit, so that it doesn't look like a screen. To understand exactly what is going on:

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

I also had this problem many times. Usually, if you add a View to the layout and you don't see it (and you don't get errors), the problem is the width / hierarchy or position (for example, when using RelativeLayout).

+6
source

All Articles