Issue
For my app I want to add buttons to a linearlayout programmatically with a background to make it look better. For the background I use a drawable. The drawable is defined as:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners
android:bottomRightRadius="24dp"
android:bottomLeftRadius="24dp"
android:topRightRadius="24dp"
android:topLeftRadius="24dp"/>
</shape>
The button is defined programaticaly by:
//make new button
Button b = new Button(this);
b.setText(someText);
b.setId(id);
b.setAllCaps(false);
b.setTextColor(getResources().getColor(R.color.textOnButton));
b.setBackground(drawable);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doAction(v);
}
});
//setParameters of Linearlayout
LinearLayout linear = findViewById(R.id.linearLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, BUTTON_HEIGHT);
params.setMargins(LEFT_MARGIN_BUTTON, TOP_MARGIN_BUTTON,RIGHT_MARGIN_BUTTON,DOWN_MARGIN_BUTTON);
linear.setOrientation(LinearLayout.VERTICAL);
//add button to linearlayout
linear.addView(b, params);
However, if I make a button with this drawable as background, it will appear as:
The white mess in the middle is some text that should appear as something like this:
Idealy I would like to change the height of the button to the default textsize of the system plus some margin. Is there way to fix this?
Solution
Use:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
In your case you can also use a simple MaterialButton
:
val b = MaterialButton(this)
b.cornerRadius = resources.getDimensionPixelOffset(R.dimen.cornerSize)
Answered By - Gabriele Mariotti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.