繁体   English   中英

Android 按钮可绘制不适合文本

[英]Android button drawable does not fit the text

对于我的应用程序,我想以编程方式将按钮添加到带有背景的线性布局中,以使其看起来更好。 对于背景,我使用可绘制对象。 可绘制对象定义为:

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

该按钮通过以下方式以编程方式定义:

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

但是,如果我用这个drawable作为背景制作一个按钮,它将显示为: 错误按钮

中间的白色混乱是一些应该像这样显示的文本: 正确的文本按钮

理想情况下,我想将按钮的高度更改为系统的默认文本大小加上一些边距。 有没有办法解决这个问题?

利用:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

在您的情况下,您还可以使用简单的MaterialButton

 val b = MaterialButton(this)
 b.cornerRadius = resources.getDimensionPixelOffset(R.dimen.cornerSize)

在此处输入图像描述

满足此目的的另一种方法是使用:

//first acquire the default text height
int textSize = (int) new Button(this).getTextSize();

//then set the height of the layout to this default text height plus some constant
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT,
     textSize + BUTTON_TEXT_MARGIN);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM