【问题标题】:Android button drawable does not fit the textAndroid按钮可绘制不适合文本
【发布时间】:2020-12-11 06:09:29
【问题描述】:

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

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

但是,如果我用这个可绘制对象作为背景制作一个按钮,它将显示为:

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

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

【问题讨论】:

    标签: java android button android-button


    【解决方案1】:

    用途:

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-09-09
        • 1970-01-01
        • 2019-12-21
        • 2014-07-16
        • 2015-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多