Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 1px sometimes 2px when specified in Android XML?

Tags:

android

I've got a desire for a one-pixel divider line, just for looks. I thought I could accomplish this using a View of height 1px, with a defined background. However, I'm getting some very odd behavior on different devices - sometimes the 1px ends up as 2px.

Take this sample layout for example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
    <View android:layout_width="fill_parent" android:layout_height="1px"
        android:background="@android:color/white" android:layout_marginBottom="4dp" />
</LinearLayout>

When run on my G1, this comes out fine. But on the Nexus One, it alternates between 1px lines and 2px lines.

Does anyone know where this is going awry? Why does Android sometimes make 1px into 2px?

Edit: To make this absolutely clear, I do not care about solving my example in particular; what I care about is being able to say "this View shall be 1px high", in any circumstance, not just this example.

like image 303
Dan Lew Avatar asked Dec 05 '25 21:12

Dan Lew


1 Answers

Are you building against SDK 1.5, or setting android:anyDensity="false"? If your app does not say it supports densities, then Android will run in compatibility mode where it makes the screen look like an mdpi screen, scaling ALL coordinates and drawing to match the real screen density. Running in an hdpi screen like Droid, this is a 1.5x scaling, so every other "pixel" will be mapped to two pixels on the screen.

Apps today should be written to support different screens, in which case the px and dp units will behave as desired on all screens.

like image 193
hackbod Avatar answered Dec 07 '25 15:12

hackbod