Android ImageButton Resolution Problems

2019-07-24 17:27发布

问题:

I want to have two buttons at the top of my program taking users to different activities. I'm having a lot of trouble with the formatting.

How can I make it so that the buttons will stretch proportionally based on the screen size? Right now, they will look OK for one screen size, then I will switch to a different one and it will appear all smushed or stretched. I've tried all of the different ScaleTypes and none seem to make a difference. I also went though and proportionally saved all of the images to the correct sizes regardimg xhdpi, hdpi, etc using Shubhayu's answer.

Here's my code so far:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/brushed_metal_background_dark"
tools:context=".HomeActivity" >

<ImageButton
    android:id="@+id/incidentsSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/incident_bar2"
    android:contentDescription="Incidents"
    android:onClick="chooseIncident"
    android:scaleType="center" />

<ImageButton
    android:id="@+id/operationalPeriodsSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/operationalperiod_bar2"
    android:contentDescription="Operational Periods"
    android:onClick="chooseOperationalPeriod"
    android:scaleType="fitCenter" />

回答1:

Change android:background to android:src that will keep the aspect ratio. Use android:scaleType="centerInside" to fit whole image inside button area and optionally use android:adjustViewBounds=true to remove empty spaces. Example:

<ImageButton
    android:id="@+id/incidentsSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:contentDescription="Incidents"
    android:onClick="chooseIncident"
    android:src="@drawable/incident_bar2"
    android:scaleType="centerInside"
    android:adjustViewBounds="true"/>

<ImageButton
    android:id="@+id/operationalPeriodsSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:contentDescription="Operational Periods"
    android:onClick="chooseOperationalPeriod"
    android:src="@drawable/operationalperiod_bar2"
    android:scaleType="centerInside"
    android:adjustViewBounds="true"/>


回答2:

I am guessing that you are trying to size the buttons evenly on the top of the screen. If that's the case then you should set android:layout_width="0dp".



回答3:

Just use android:layout_width = "wrap_content"