Reputation: 729
Button btnDone = new Button(Mcontex);
btnDone.setWidth(100); //Not working
btnDone.setMinimumWidth(20); //also not working
btnDone.setGravity(Gravity.RIGHT); // Not button move, just text move
btnDone.setText("Done");
btnDone.setTextColor(Color.WHITE);
layoutbutton.addView(btnDone, new LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
layoutmain.addView(layoutbutton);
I want to move this button to right of layoutbutton. I can't adjust the button width, which part I wrong. In this code, I think the button width is in fill parent, I can't control.
Upvotes: 0
Views: 904
Reputation: 116
Supposing your layoutButton view is LinearLayout, you should do:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutbutton.addView(btnDone,layoutParams);
Upvotes: 0
Reputation: 300
to set width and height use:
_btnDone.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
to move the button to the right, change the layout width to "MATCH_PARENT" and set the gravity of the layout to right
layoutbutton.setGravity(Gravity.RIGHT);
Upvotes: 1
Reputation: 116
You've a couple of errors. One of them is that you should use setLayoutGravity instead of setGravity as setGravity aligns the content inside the view. In your case, as you say in the comment, the text (which is the content inside the button) is moving to the right. setLayoutGravity is the right one for aligning the child with its parent.
On the other hand, your container view (layoutButton) has a width of wrap_content, so it does not fill the whole width of the screen and will have the size of its children (in your case 100 px of the button).
Conclusion:
-You must use setLayoutGravity in your button.
-Switch your layoutButton layoutParams width to MATCH_PARENT.
Upvotes: 0