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

Android:根据按钮文本对齐文本,android,android-layout,alignment,android-relativelayout,Android,Android Layout,Alignment,Android Relativelayout,我有一个RelativeLayout,其中有一个按钮,下面有一个文本。我想根据按钮文本对齐文本,即它从左侧开始的宽度与按钮文本相同 我尝试使用android:layout\u alignLeft=“@id/myButton”,但这会将其与按钮边缘对齐,而不是与按钮文本对齐 有什么办法可以做到这一点吗 在我的布局XML中,按钮和文本如下所示: <Button android:id="@+id/myButton" android:layout_width="200dp"

我有一个
RelativeLayout
,其中有一个按钮,下面有一个文本。我想根据按钮文本对齐文本,即它从左侧开始的宽度与按钮文本相同

我尝试使用android:layout\u 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" />

我不确定如何在XML中实现它,但我会以编程方式尝试

myTextView.setPadding(myButton.getPaddingLeft(),0,0,0)

编辑:或者,你可以用xml设置按钮和文本视图的填充,如果你使用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);

请在textview内容中使用此字段。你也会得到同样的结果。它工作正常。请使用它。你必须从代码中通过编程来完成它。。 代码如下

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());
边距和填充也一样