2014-09-11 140 views
-1

我非常新的Android我有這樣的MainActivity:爲什麼我不能膨脹佈局?

static TableRow row; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     for (int i = 0; i < 10; i++) { 
      View v = getLayoutInflater().inflate(R.layout.row, null); 
      TextView text = (TextView) v.findViewById(R.id.myText); 
      text.setText("Test"); 
     } 
    } 

我想添加一個行的表十次,每一個有Test字文本視圖裏面,但我想這是語法上不使用任何準備好的佈局,因爲在先進的情況下,我可以從XML讀取,我不知道我將需要的行數。 佈局row包含:

<?xml version="1.0" encoding="utf-8"?> 
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/myRow" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center_horizontal" 
    android:weightSum="1" > 

    <TextView 
     android:id="@+id/myText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

</TableRow> 

activity_main.xml中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.bahisdoktoru.MainActivity" > 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

</RelativeLayout> 

當我運行應用程序,我沒有得到任何東西只是世界您好文本(activity_main.xml中的作品),但行和他們裏面的文本不顯示(我認爲row.xml不起作用)。 我希望你能告訴我如果我錯過任何東西或者如果我寫錯了什麼我怎麼能顯示我想要的文法行?

+0

如果你不會知道你會多少行需要,那麼你supouse使用ListView和一個適配器,而不是膨脹的佈局,因爲你的做法是不是更大的數據集的優化,你的應用程序將簡單地凍結 – Hellboy 2014-09-11 12:27:52

+0

你是不是在佈局的任何位置添加新增的「View v」。你需要添加一個佈局到你的層次結構中,以便顯示:) – 2014-09-11 12:52:04

回答

0
use below code instead of yours :- 

    for (int i = 0; i < 10; i++) { 
    LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       View v = inflater.inflate(R.layout.row, null); 
       TextView text = (TextView) v.findViewById(R.id.myText); 
       text.setText("Test"); 
      } 
+0

我使用這個,但仍然是同樣的問題,不顯示'row.xml' – 2014-09-11 12:34:13