将 TextView 设置到 LinearLayout 的右侧(垂直)

Set TextView To Right Of LinearLayout(Vertical)

我一直在 Google 中搜索这个答案。我一直在尝试将 TextView 设置为与垂直 LinearLayout 的右侧对齐。然而,设置参数并使用这个...

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

不起作用。我几乎可以肯定这是因为我将宽度设置为 WRAP_CONTENT.

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

问题是,如果我将宽度设置为 MATCH_PARENT,那么(正如预期的那样)TextView 的背景颜色会填满屏幕的整个宽度。我并不是要将文本的重心设置为右侧。我试图让整个 TextView 与 LinearLayout 的右侧对齐,同时保持宽度等于其中文本的大小。

有人能帮忙吗???

RelativeLayout.ALIGN_PARENT_RIGHT 不起作用,因为它是 RelativeLayout 的规则,不适用于 LinearLayout

假设您的 LinearLayout 设置为 match_parent 那么您应该应用重力。只需将以下内容添加到 TextView

android:layout_gravity="end"

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

注意:布局重力和视图重力是不同的东西 - 布局重力设置视图在其布局中的位置,而重力设置视图中内容的重力