就我而言,我使用的是 AppCompatImageButton(和 AppCompat)。事实证明,如果我将密度调整后的图像保存在各种可绘制文件夹中:drawable-ldpi、drawable-mdpi、drawable-hdpi 等。那么按钮将不会缩放。相反,我必须在 drawable-nodpi 中为每个按钮放置一个可绘制对象。确保 drawable-nodpi 按钮图像是您需要的最大尺寸。Android 不会放大按钮大小;但是,它可以缩小尺寸。我在 XML 中创建了一个按钮,如下所示:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:meter="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatImageButton
android:id="@+id/button"
style="@style/ButtonStyle"
android:baselineAlignBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="0dp"
android:minWidth="0dp"
app:srcCompat="@drawable/button_selector"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/button"
android:focusable="true">
</RelativeLayout>
<!-- styles.xml -->
<style name="ButtonStyle" parent="MyAppTheme">
<item name="android:scaleType">centerInside</item>
<item name="android:adjustViewBounds">true</item>
<item name="colorControlHighlight">@color/buttonColorPressed</item>
<item name="colorButtonNormal">@color/buttonColor</item>
</style>
<!-- v21/styles.xml -->
<style name="TargetButton" parent="MyAppTheme">
<item name="android:scaleType">centerInside</item>
<item name="android:adjustViewBounds">true</item>
<item name="colorControlHighlight">@color/buttonColorPressed</item>
<item name="colorButtonNormal">@color/buttonColor</item>
<item name="android:elevation">@dimen/button_elevation</item>
</style>
<!-- drawable/button_selector.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/button"/>
</selector>
<!-- drawable/button.xml -->
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/ic_button"
android:gravity="center" />
<!-- drawable/button_pressed.xml -->
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/ic_button_pressed"
android:gravity="center" />
接下来,在 onCreate 中,当您检索按钮时,调用adjustButtonSize(我把它放在我的基类中):
mButton = (AppCompatImageButton) findViewById(R.id.button);
adjustButtonSize(mButton);
public void adjustButtonSize(AppCompatImageButton button) {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
ViewGroup.LayoutParams params = button.getLayoutParams();
params.height = height / 10; // 10%
params.width = ((width * 20) / 100); // 20%
button.setLayoutParams(params);
}