2011-01-09 78 views
235

我有我創建一個程序相對佈局:如何以編程方式設置相對佈局中按鈕的layout_align_parent_right屬性?

RelativeLayout layout = new RelativeLayout(this); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, 
      LayoutParams.WRAP_CONTENT); 

現在我有,我想在這個相對佈局添加兩個按鈕。但問題是兩個按鈕都顯示在RelatiiveLayout的左側相互重疊。

buttonContainer.addView(btn1); 
buttonContainer.addView(btn2); 

現在我想知道我如何通過編程設定按鈕的的android:layout_alignParentRight="true「 或android:layout_toLeftOf="@id/btn"屬性,就像我們在XML呢?

回答

561

您可以使用View.getLayoutParams從代碼中訪問任何LayoutParams。你只需要非常清楚你的訪問權限是什麼LayoutParams。這通常是通過檢查包含ViewGroup是否有一個LayoutParams內部孩子,然後這是你應該使用的。在你的情況下,它是RelativeLayout.LayoutParams。你會使用RelativeLayout.LayoutParams#addRule(int verb)RelativeLayout.LayoutParams#addRule(int verb, int anchor)

您可以通過代碼來得到它:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams(); 
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of); 

button.setLayoutParams(params); //causes layout update 
10
  1. 你需要爲 按鈕創建和id你需要REFFERENCE: btn1.setId(1);
  2. 可以使用PARAMS變量 參數添加到您的佈局,我 認爲該方法addRule(),檢查 out of the android java docs for this LayoutParams object。
+0

我將高度讚賞任何一段代碼。我沒有在按鈕中找到任何方法。 – 2011-01-09 11:30:42

+0

由於setId正在使用@IdRes進行註釋,因此設置ID無助於預期實際資源ID,而不僅僅是一個數字。 – 2015-05-20 06:45:13