2013-07-01 68 views
0

我有一個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); 

回答

2

我認爲你應該爲TextView創建一個新的RelativeLayoutParams,因爲你得到一個帶有規則的params來對齊其父(params of button)的權限。

你也必須給id一個按鈕。

你這樣做:

Button button = new Button(this); 
upgradeButton.setId(12345); 

,你應該到一個按鈕給ID:

Button button = new Button(this); 
button.setId(12345); 

證明了這一點代碼:

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 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
layoutForAlignmentX.addRule(RelativeLayout.LEFT_OF, button.getId()); 
layout.addView(myTextView, layoutForAlignmentX); 

很抱歉,如果你不明白的地方,我的英文不太好....

+0

謝謝!將ID設置爲upgradeButton是我在我的主帖中修復的一個錯誤,但問題是我應該像你說的那樣創建一個新的RelativeLayoutParams。 – Bobby

2

我覺得你的問題是這一行:

layoutForAlignmentX.addRule(RelativeLayout.LEFT_OF, myTextView.getId()); 

它應該是:

layoutForAlignmentX.addRule(RelativeLayout.LEFT_OF, button.getId()); 

這樣,你在你的按鈕的左側設置你的TextView。

+0

不,這是一個錯字當張貼在這裏。抱歉。 – Bobby