首页 > 解决方案 > MaterialButton 与 Button 的大小差异

问题描述

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

如何使用 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();
}

}

截屏

标签: javaandroidmaterial-designandroid-buttonmaterial-components-android

解决方案


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

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

推荐阅读