RelativeLayout.RIGHT_OF不起作用 [英] RelativeLayout.RIGHT_OF does not work

查看:240
本文介绍了RelativeLayout.RIGHT_OF不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在现有的相对布局中以编程方式创建一个textview和一个按钮.这个想法是将textview放在parentView(relativeLayout)的左上角,然后在textView的右边添加按钮.但是在应用程序中,它们看起来像在一个地方.该按钮在textView的前面,而不是在右边.请给我一些建议.

I am trying to create a textview and a button programmatically in the existing relative layout. The idea is to put the textview in the left corner of the parentView(relativeLayout) and add then the button to the right of the textView. But in the app it looks like they are on the one place. The button is in front of textView, not on the right. Please, give me some advice.

代码:

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

推荐答案

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

For RelativeLayout.LayoutParams rules, 0 means false, and only applies to rules that don't refer to sibling Views, such as CENTER_IN_PARENT. Since you've set your TextView's ID to 0, the RIGHT_OF rule you're adding is being ignored, as false doesn't make sense with that.

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

To remedy this, simply set the TextView's ID to any positive int value; e.g., 1.

这篇关于RelativeLayout.RIGHT_OF不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆