材料按钮尺寸与按钮的尺寸差异

我正在设置一个新的应用程序,并遇到了材料按钮的高度与我设置的大小不匹配的事实。所以我尝试了常规按钮,正如你们在下面的屏幕截图中看到的那样。按钮具有不同的高度,尽管它们的高度与您在我的代码中看到的高度相同。

如何使用MaterialButton获得正常高度?

谢谢。

公共类 MainActivity 扩展了 AppCompatActivity {

MaterialButton materialButton;
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setId(getGeneratedId());

    setContentView(linearLayout);

    int buttonWidth = getResources().getDimensionPixelSize(R.dimen.buttonWidth);
    int buttonHeight = getResources().getDimensionPixelSize(R.dimen.buttonHeight);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(buttonWidth, buttonHeight);

    materialButton = new MaterialButton(this);
    materialButton.setId(getGeneratedId());
    materialButton.setLayoutParams(layoutParams);
    materialButton.setBackgroundColor(Color.BLUE);
    materialButton.setText("MatrialB");
    materialButton.setTextColor(Color.WHITE);


    button = new Button(this);
    button.setId(getGeneratedId());
    button.setLayoutParams(layoutParams);
    button.setBackgroundColor(Color.RED);
    button.setText("Button");
    button.setTextColor(Color.WHITE);

    linearLayout.addView(materialButton);
    linearLayout.addView(button);
    
}

Integer getGeneratedId() {
    return ViewCompat.generateViewId();
}

}

Screenshot


答案 1

我相信MaterialButton的顶部和底部的空间来自/这对我来说是材料组件1.0.0。我不确定如何以编程方式设置这些,但它可以在xml中轻松完成:android:insetTopandroid:insetBottom6dp

<com.google.android.material.button.MaterialButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:insetBottom="0dp"
      android:insetTop="0dp"/>

答案 2

具有默认样式,其值为 和 值为 。MaterialButtoninsetBottominsetTop6dp

您可以在没有/使用垂直插图的情况下检查差异:

enter image description here

您可以使用以下命令更改默认值:

<com.google.android.material.button.MaterialButton
    android:insetTop="0dp"
    android:insetBottom="0dp"

或以编程方式(至少需要)与:1.3.0-alpha03

    button.insetTop = 0
    button.insetBottom = 0

推荐