简体   繁体   English

将TextView设置为LinearLayout(Vertical)的右侧

[英]Set TextView To Right Of LinearLayout(Vertical)

I've been searching all over the Google for this answer. 我一直在整个Google搜索此答案。 I've been trying to set a TextView to align with the right of my vertical LinearLayout. 我一直试图将TextView设置为与我的垂直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. 我几乎可以肯定这是因为我已将宽度设置为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. 问题是,如果我将宽度设置为MATCH_PARENT,则(如预期的那样)TextView的背景色将填满屏幕的整个宽度。 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. 我正在尝试使整个TextView与LinearLayout的右侧对齐,同时保持宽度等于其中的文本大小。

Can anyone help??? 谁能帮忙???

RelativeLayout.ALIGN_PARENT_RIGHT does not work because it is a rule for RelativeLayout , not for LinearLayout RelativeLayout.ALIGN_PARENT_RIGHT不起作用,因为这是RelativeLayout的规则,而不是LinearLayout的规则

Presuming your LinearLayout is set to match_parent then you should apply gravity. 假设将LinearLayout设置为match_parent ,则应应用重力。 Just add the following to the TextView 只需将以下内容添加到TextView

android:layout_gravity="end"

The programmatic equivalent being to adjust the layout params on the TextView: 程序上等效的方法是调整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 注意 :布局重力和视图重力是不同的东西-布局重力设置视图在其布局中的位置,而重力设置视图中内容的重力

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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