简体   繁体   中英

How to set the align parent right attribute of TextViews in relative layout programmatically

I have a relative layout which I am creating programmatically:

 RelativeLayout layout = new RelativeLayout( this );
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);

Now I have two TextViews which I want to add in this relative layout. But the problem is both TextViews are being shown on the left of the RelativeLayout overlapping on each other.

textViewContainer.addView(textView1);
textViewContainer.addView(textView2);

Now I want to know how can I programmatically set the the

`android:layout_alignParentRight="true"`

or

`android:layout_toLeftOf="@id/textView"` 

attribute of TextViews as we do in the xml?

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can get to it via code:

   RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)textView.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

textView.setLayoutParams(params); //causes layout updat

使用方法addrule

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

You need to align LayoutParams to each view:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

Then add appropriate rule to each view:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 

to the first one and

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);

to the second one.

then apply it to the view:

view.setLayoutParam(params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM