我有一個Button和一個TextView。我正在嘗試將按鈕對齊到屏幕右側,然後將TextView放在屏幕的左側,但它不起作用。下面的代碼將按鈕放置在正確的位置,一直到右側,但是當TextView將它放在屏幕上時,它會將按鈕從屏幕上敲下來,並將按鈕所在的TextView的位置替換掉。我不明白爲什麼這樣做?Android RelativeLayout ALIGN_LEFT不工作
RelativeLayout layout = (RelativeLayout)findViewById(R.id.mainLayout);
Button button = new Button(this);
button.setId(12345);
RelativeLayout.LayoutParams layoutForAlignment = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutForAlignment.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(button, layoutForAlignment);
TextView myTextView = new TextView(getApplicationContext());
myTextView.setText("Testing");
RelativeLayout.LayoutParams layoutForAlignmentX = (RelativeLayout.LayoutParams) button.getLayoutParams();
layoutForAlignmentX.addRule(RelativeLayout.LEFT_OF, button.getId());
layout.addView(myTextView, layoutForAlignmentX);
謝謝!將ID設置爲upgradeButton是我在我的主帖中修復的一個錯誤,但問題是我應該像你說的那樣創建一個新的RelativeLayoutParams。 – Bobby