我有一个按钮和一个 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);