2017-08-23 116 views
-5

我有一個如下所示的xml。以編程方式設置Android組件

<LinearLayout 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:padding="16dp"> 

<LinearLayout 
    android:id="@+id/etMsisdn" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <LinearLayout 
     android:id="@+id/allView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"> 
     <EditText 
      android:id="@+id/msisdn" 
      android:layout_marginRight="4dp" 
      android:layout_weight="1" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:backgroundTint="@color/colorPrimaryDark" 
      android:hint="MSISDN" 
      android:inputType="numberDecimal" 
      /> 
     <ImageView 
      android:layout_width="60px" 
      android:layout_height="match_parent" 
      android:src="@drawable/scan"/> 
    </LinearLayout> 
</LinearLayout> 
............ 
Another View 
............ 
</LinearLayout> 

如何添加的EditText和ImageView的編程水平的LinearLayout(allView)內,並添加垂直的LinearLayout內allView(etMsisdn),同時保持相同屬性的XML格式。

的EditText上和ImageView的R上的MSISDN的EditText下面應該

The EditText and ImageView r supposed to below the msisdn edittext

回答

0

你需要去的最LinearLayout(先在你的佈局之一)的引用,所以最好的辦法是給它的編號:

<LinearLayout 
    android:id="@+id/myContainer" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="16dp"> 

然後,你需要獲得參考這種佈局,並添加了孩子的意見,就像這樣:

LinearLayout containerLayout = (LinearLayout)findViewById(R.id.myContainer); 
containerLayout.addView(yourView1); 
containerLayout.addView(yourView2); 

要設置所需的佈局排列,您可以手動設置所需LayoutParams(見this answer in SO),或者你可以膨脹的佈局,並把它添加到您當前的佈局,而不是兩個單獨的視圖(EditTextImageView)(見this answer in SO )。

+0

這篇已經,,,但不可能得到的EditText和imageview的水平對齊 – BrenDonie

+0

那就是另一回事了。您可以手動添加所需的LayoutParams(請參閱[在SO中的此答案](https://stackoverflow.com/questions/5715612/how-to-set-setlayoutparams-for-linear-layout-elements)),或者您可以充氣佈局(見[這個答案在SO](https://stackoverflow.com/questions/5342121/inflate-a-view-layout-into-another-layout#5343733))。 –

+0

我已經用以前的信息更新了答案。 –

0

這裏是您的解決方案

LinearLayout allview=(LinearLayout)findViewById(R.id.allView); 

EditText edt=new EditText(this); 
ImageView img=new ImageView(this); 
allview.addView(edt); 
allview.addView(img); 

把這個在您的活動

+0

這樣做會水平添加imgview和edittext不垂直 – BrenDonie

+0

比您可以設置參數或更改方向 –

0

您必須使用addView方法在佈局對象。 但是,如果您想在主佈局中添加更多次相同的「子佈局」,最好使用「子部件」創建xml佈局並以編程方式添加它。讓我知道如果第二種情況是你需要提供代碼。

+0

我想在線性佈局(主)內添加線性佈局(子)。但是在子線性佈局中包含edittext和imageview等其他視圖 – BrenDonie

相關問題