2
votes
  1. New -> Android project for testing the problem
  2. Code for Test.java:

    package test.density.yeah;

    import android.app.Activity;
    import android.os.Bundle;
    
    public class TestActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }
    
  3. Code for main.xml:

    <ImageButton
    android:background="@null"
    android:src="@drawable/icon"
    android:layout_width="200dp"
    android:layout_height="200dp">
    </ImageButton>
    
  4. Started emulator with settings:

Resolution - 480x800

Avstracted LCD Density - 190

RESULT:

http://cs5961.userapi.com/u68152416/-3/y_ef134df2.jpg

After that I've started emulator with such settings:

Resolution - 480x800

Avstracted LCD Density - 240

RESULT:

http://cs5961.userapi.com/u68152416/-3/y_8b99507b.jpg

Emulator settings for the first test mathes my HTC HD2 characteristics and second is the same as the HTC Sensation XL is. When running this test app on them it is the same problem. HD2 (480x800, 190dpi) - small image, Sensation (480x800, 240dpi) - huge image.

So why "density independent pixels" do not work?

2

2 Answers

4
votes

It works fine, but there's a twist you need to know about.

You're using the src attribute on the View. If you do that, the View will be sized according to the bitmap size, and you'd normally have different versions for the various densities, mdpi, hdpi, xhdpi etc. It will ignore layout_height and layout_width.

If you want your View to ignore the bitmap size and use the layout_width and layout_height values to force the size, you need to use the background attribute, not src.

<ImageButton
    android:background="@drawable/icon"
    android:layout_width="200dp"
    android:layout_height="200dp">
</ImageButton>
1
votes

May be the image scaling make your result gone wrong, you can read more about image scaling here:

http://thebigbyte.blogspot.com/2009/12/android-how-to-scale-image-in-imageview.html

You can test the result by change the ImageButton xml to

<ImageButton
android:background="#ffffff"
android:layout_width="200dp"
android:layout_height="200dp">
</ImageButton>