简体   繁体   中英

Set TextView To Right Of LinearLayout(Vertical)

I've been searching all over the Google for this answer. I've been trying to set a TextView to align with the right of my vertical LinearLayout. However, setting the params and using this...

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

doesn't work. I'm almost certain it is because I have set the width to WRAP_CONTENT.

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

The problem is, if I set the width to MATCH_PARENT then (as expected) the background color of the TextView fills the whole width of the screen. I am not trying to set the gravity of the text to the right. I'm trying to get the whole TextView to align with the right of the LinearLayout while keeping the width equal to the size of the text inside it.

Can anyone help???

RelativeLayout.ALIGN_PARENT_RIGHT does not work because it is a rule for RelativeLayout , not for LinearLayout

Presuming your LinearLayout is set to match_parent then you should apply gravity. Just add the following to the TextView

android:layout_gravity="end"

The programmatic equivalent being to adjust the layout params on the TextView:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.END; //despite the confusing name, this is on Layout params and this is layout_gravity
params.weight = 1.0f;
textView.setLayoutParams(params);

Note : Layout Gravity and View Gravity are different things - Layout Gravity sets the views position within it's layout, whereas gravity sets the gravity for the content within the view

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