我正在尝试在现有的相对布局中以编程方式创建textview和按钮。想法是将textview放在parentView(relativeLayout)的左角,然后添加textView右侧的按钮。但在应用程序中,它看起来像是在一个地方。该按钮位于textView前面,而不是右侧。拜托,给我一些建议。
代码:
TextView textView = new TextView(getActivity().getApplicationContext());
textView.setText("...");
textView.setTextColor(Color.GRAY);
int id = 0;
textView.setId(id);
final RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.setMargins(16, 16, 0, 0);
textView.setLayoutParams(params);
notificationContentLayout.addView(textView, params);
Button customerButton = new Button(getActivity().getApplicationContext());
customerButton.setText("...");
customerButton.setTextColor(Color.parseColor("#00b3ff"));
customerButton.setBackgroundColor(Color.TRANSPARENT);
id = id + 1;
customerButton.setId(id);
final RelativeLayout.LayoutParams paramsForButton =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
paramsForButton.addRule(RelativeLayout.RIGHT_OF, textView.getId());
paramsForButton.addRule(RelativeLayout.ALIGN_PARENT_TOP); // with or without that rule everything is the same
// paramsForButton.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
paramsForButton.setMargins(10,0, 16, 0);
customerButton.setLayoutParams(paramsForButton);
notificationContentLayout.addView(customerButton, paramsForButton);
答案 0 :(得分:1)
对于RelativeLayout.LayoutParams
规则,0
表示false
,仅适用于未引用同级View
的规则,例如CENTER_IN_PARENT
。由于您已将TextView
的ID设置为0
,因此您要添加的RIGHT_OF
规则将被忽略,因为false
对此没有意义。
要解决此问题,只需将TextView
的ID设置为任何正int
值;例如,1
。