2013-03-04 28 views
-6

我想要將xml轉換爲android代碼。XML到Java中的Android代碼

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/LinearLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".MainActivity" > 

    <TextView 
     android:id="@+id/screen" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

     <Button 
      android:id="@+id/connectBtn" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="Connect" /> 

     <TextView 
      android:id="@+id/space" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" /> 

     <Button 
      android:id="@+id/disconnectBtn" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="Disconnect" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

     <Button 
      android:id="@+id/btn1" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="@string/btn1_txt" /> 

     <Button 
      android:id="@+id/btn2" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="@string/btn2_txt" /> 

     <Button 
      android:id="@+id/btn3" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="@string/btn3_txt" /> 
     </LinearLayout> 

上面的代碼需要轉換爲java代碼。

爲此,我需要在java中創建多個線性佈局。那是正確的方法嗎?如果不是什麼是正確的方式?

+0

視圖你想要這個機器人佈局Java佈局? – 2013-03-04 13:14:51

+0

我想在java代碼中編寫這個xml – snnlaynnkrdsm 2013-03-04 13:18:16

+0

請確定搜索如何動​​態創建android佈局 – 2013-03-04 13:18:45

回答

2

您可以通過做誇大其觀點:

LayoutInflater inflater = (LayoutInflater)context.getSystemService 
    (Context.LAYOUT_INFLATER_SERVICE); 
inflater.inflate(...); 

或者,你可以簡單地創建一個像

final LinearLayout l = [...] 
//add stuff 
l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 
//etc...