RelativeLayout.RIGHT_OF不起作用

时间:2016-06-29 12:55:23

标签: android android-layout

我正在尝试在现有的相对布局中以编程方式创建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);

1 个答案:

答案 0 :(得分:1)

对于RelativeLayout.LayoutParams规则,0表示false,仅适用于未引用同级View的规则,例如CENTER_IN_PARENT。由于您已将TextView的ID设置为0,因此您要添加的RIGHT_OF规则将被忽略,因为false对此没有意义。

要解决此问题,只需将TextView的ID设置为任何正int值;例如,1