Terry
Terry

Reputation: 14867

Android: align a text according to button text

I have a RelativeLayout where I have a button, and below a text. I want to align the text according to the button text, i.e. that it starts at the same width from the left like the button text.

I tried using android:layout_alignLeft="@id/myButton" but that aligns it to the edge of the button, not of the button text.

Is there a way I can achieve this?

In my layout XML, button and text look like this:

<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" />

Upvotes: 4

Views: 194

Answers (4)

B3738
B3738

Reputation: 51

What if you use a Java code:

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

Upvotes: 0

johntheripp3r
johntheripp3r

Reputation: 989

You have to do it programatically from your code.. Code is as follows.

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

You can also get the margins and paddings and also text alignments like..

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

// Alternative code of above

myTextView.setTextAlignment(myButton.getTextAlignment());

same thing goes with margins and padding.

Upvotes: 0

Arun Kumar
Arun Kumar

Reputation: 100

Please use this field android:gravity="center" into Your textview Content. You Will get the same..Its Working fine..Please Use this

Upvotes: 1

Embattled Swag
Embattled Swag

Reputation: 1469

Not sure how I would do it in XML, but programmatically I would try

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

Edit: Or, duh, you could just set the button's and textview's padding in xml

Upvotes: 0

Related Questions