2011-09-01 85 views
4

XML的ViewGroup我希望能夠到一個視圖中的代碼添加到一個已經存在的XML佈局:添加視圖,以現有的代碼

 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); 

當創建一個新的LinearLayout代碼它的工作原理,但是當使用像上面的代碼中的資源,它不會。

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> 
+0

哪個錯誤給你在logcat? – Dayerman

+0

錯誤/ AndroidRuntime(8357):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.androidABC/com.example.androidABC.Common_ActivityList}:java.lang.NullPointerException 09-01 14:59:57.889: ERROR/AndroidRuntime(8357):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2753) 09-01 14:59:57.889:ERROR/AndroidRuntime(8357):at android.app.ActivityThread.handleLaunchActivity(ActivityThread。 java:2769) 09-01 14:59:57.889:ERROR/AndroidRuntime(8357):at android.app.ActivityThread.access $ 2500(ActivityThread.java:129) – Klau3

回答

6

嘗試使用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); 

如果這樣都不行,請從logcat中添加錯誤。

此外,你應該從機器人更改屬性:layout_width = 「FILL_PARENT」 到Android:在common_list.xml YOUT的LinearLayout layout_width = 「WRAP_CONTENT」,也做同樣的事情到你的TextView在common_list.xml

爲什麼?因爲您的佈局是面向橫向的並且它填充整個屏幕空間。你的TextEdit可以填充你的佈局所需的空間(在這種情況下,它是整個屏幕空間)。現在,當您添加另一個TextView時,它會正確地添加到第一個TextEdit的右側,所以它就像是在屏幕之外。要準確理解發生了什麼:

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

我也有過這個問題多次。通常如果你添加視圖到佈局,而你沒有看到它(並且你沒有錯誤),問題是寬度/高度或位置(例如當你使用RelativeLayout時)。

+0

現在它打開活動,但它不顯示創建了TextView。這裏是我使用的代碼:'LinearLayout ll =(LinearLayout)LayoutInflater.from(this).inflate(R.layout.common_list,null); \t \t TextView tv = new TextView(this); \t \t tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); \t tv.setText(「sample text」); \t ll.addView(tv); \t \t setContentView(ll); ' – Klau3

+0

請附上您的common_list.xml。 –

+0

我將它添加到問題描述 – Klau3

相關問題