Lisa Semyonova
Lisa Semyonova

Reputation: 117

RelativeLayout.RIGHT_OF does not work

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.

the code:

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

Upvotes: 1

Views: 1113

Answers (1)

Mike M.
Mike M.

Reputation: 39191

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.

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

Upvotes: 2

Related Questions