在我的情況下,我使用AppCompatImageButton(和AppCompat)。 事實證明,如果我將密度調整圖像保存在各種可繪製的 文件夾中:drawable-ldpi,drawable-mdpi,drawable-hdpi等,那麼按鈕將不會縮放。 相反,我不得不爲放置一個drawable-nodpi中的每個按鈕。 確保可繪製的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);
}
重要的是要注意:你應該應用包含你的View的'ViewGroup'的'LayoutParams'。也就是說,如果你的按鈕在'RelativeLayout'裏面,你應該使用'RelativeLayout.LayoutParams'。 – agamov
那麼,如何指定單位? –
您應該將尺寸值乘以顯示比例,因爲構造函數需要像素而不是dp。 像這樣: widthInPixels = getResources()。getDisplayMetrics()。密度* widthInDp; –