0

我有一个按钮和一个 TextView。我试图将按钮一直对齐到屏幕的右侧,然后将 TextView 放在它的左侧,但它不起作用。下面的代码将按钮放置在正确的位置,一直到右侧,但是当将 TextView 放在屏幕上时,它会将按钮从屏幕上敲下来并在按钮所在的位置替换 TextView。我不明白它为什么这样做?

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);
4

2 回答 2

3

我认为您应该为 TextView 创建一个新的 RelativeLayoutParams,因为您正在获得一个参数,该参数具有对齐其父级右侧的规则(按钮的参数)。

您还必须为按钮提供一个 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);

抱歉,如果您有什么不明白的地方,我的英语不是很好......

于 2013-07-02T14:38:25.710 回答
2

我认为你的问题是这一行:

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

它应该是:

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

这样,您就可以在按钮的左侧设置 textview。

于 2013-07-01T14:40:04.823 回答