Android : Button gravity set programmatically not working

时间:2016-07-11 20:53:58

标签: android button gravity

I can't set the text gravity of a Button dynamically.

My button is in a LinearLayout, with a vertical orientation.

When I create a button in the xml file, everything works as expected :

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|start"
    android:text="My button"/>

But when I create the same button dinamically, text remains centered instead of being left aligned:

Button myButton = new Button(context);
myButton.setText("My button");
myLinearLayout.addView(myButton);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) myButton.getLayoutParams();
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.CENTER_VERTICAL | Gravity.START;

Do you have any idea why the text remains centered when I create my button programmatically? For your information, I need to be in API 16 (so myButton.setTextAlignment() won't work).

Thanks for your help!

1 个答案:

答案 0 :(得分:1)

Change the code above as follows and let me know which of them works:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_VERTICAL | Gravity.START;

Button myButton = new Button(context);
myButton.setText("My button");
myButton.setLayoutParams(params);

myLinearLayout.addView(myButton);

OR

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_VERTICAL | Gravity.START;

Button myButton = new Button(context);
myButton.setText("My button");

myLinearLayout.addView(myButton, params);

OR

Button myButton = new Button(context);
myButton.setText("My button");
myButton.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
myLinearLayout.addView(myButton);