Android:根据按钮文本对齐文本

4

我有一个RelativeLayout布局,其中有一个按钮和下方的文本。我想让文本与按钮文本对齐,即以与按钮文本相同的宽度从左侧开始对齐。

我尝试使用android:layout_alignLeft="@id/myButton", 但这会将其与按钮的边缘对齐,而不是按钮文本的边缘。

我该如何实现这一点?

在我的布局XML中,按钮和文本如下所示:

<Button
    android:id="@+id/myButton"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="16dp"
    android:text="Some text" />

<TextView
    android:id="@+id/myTextView"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignLeft="@id/myButton"
    android:layout_below="@id/myButton"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="16dp"
    android:text="Some text"
    android:textAppearance="?android:attr/textAppearanceMedium" />
4个回答

1
请在您的TextView内容中使用此字段android:gravity="center"。您将获得相同的效果,它可以正常工作。请使用此功能。

0
不确定我该如何在 XML 中实现它,但是在编程上,我会尝试
myTextView.setPadding(myButton.getPaddingLeft(),0,0,0)

编辑:或者,嗯,你可以在xml中设置按钮和文本视图的填充。


0

如果您使用Java代码:

TextView txt = (TextView) findViewById(R.id.myTextView);
Button btn = (Button) findViewById(R.id.myButton);

    txt.setPadding(10, 0, 0, 0);
    btn.setPadding(10, 0, 0, 0);

0

你必须从你的代码中以编程方式完成它。 代码如下。

RelativeLayout.LayoutParams rParams = ((TextView)findViewById(R.id.myTextView)).getLayoutParams();
rParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.myButton); // Or you can also add other rules like -- RelativeLayout.ALIGN_BASELINE or whatever you want to do. Check our Relative layout API docs.
((TextView)findViewById(R.id.myTextView)).setLayoutParams(rParams);

你还可以获取边距、填充以及文本对齐方式,例如..

((TextView))findViewById(R.id.myTextView)).setTextAlignment((Button))findViewById(R.id.myButton).getTextAlignment));

// 上述代码的替代方案

myTextView.setTextAlignment(myButton.getTextAlignment());

边距和内边距也是同样的道理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接