某些平板电脑上的英寸/ dp值错误

时间:2017-11-09 18:42:12

标签: android android-layout units-of-measurement

我的客户希望在他的应用中使用内置标尺,以便在不携带其他工具的情况下测量某些事物。如果我在布置标尺时使用 单位,它适用于我的大多数测试设备。 Android Studio虽然应该使用 dp 而不是 中的 来警告我,因为某些设备会显示不准确的英寸单位。当我在我的亚马逊Fire 7英寸平板电脑上进行测试时,哈希标记间隔太大。我的理解是160dp应该总是等于1英寸,所以我尝试分别切换到160dp和320dp我的1英寸和2英寸哈希标记。这次,哈希标记太靠近了。请参阅下面的截图。黑色标记使用英寸;红色标记使用dp。正确的大小位于黑色和红色标记之间。

如何在所有设备上指定或转换为正确的英寸值?我更喜欢用XML指定所有值,但我非常愿意使用Java代码根据需要调整布局。此外,是否有一种编程方式来发现给定设备上的英寸单位是否正确?

感谢您的帮助。

这是我的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <View
        android:id="@+id/one_inch_left"
        android:layout_width="@dimen/ruler_hash_width"
        android:layout_height="1px"
        android:layout_marginTop="1in"
        android:background="@color/solid_black"
        app:layout_constraintTop_toBottomOf="parent"/>


    <View
        android:id="@+id/two_inch_left"
        android:layout_width="@dimen/ruler_hash_width"
        android:layout_height="1px"
        android:layout_marginTop="2in"
        android:background="@color/solid_black"
        app:layout_constraintTop_toBottomOf="parent"/>


    <View
        android:id="@+id/one_inch_left2"
        android:layout_width="@dimen/ruler_hash_width"
        android:layout_height="1px"
        android:layout_marginTop="160dp"
        android:background="@color/red_button_color"
        app:layout_constraintTop_toBottomOf="parent"/>


    <View
        android:id="@+id/two_inch_left2"
        android:layout_width="@dimen/ruler_hash_width"
        android:layout_height="1px"
        android:layout_marginTop="320dp"
        android:background="@color/red_button_color"
        app:layout_constraintTop_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>

enter image description here

1 个答案:

答案 0 :(得分:0)

我不相信只有XML才能解决这个问题;一个dp应该是&#34;大约&#34; 160dpi的一个像素,但这不是一个很难保证。

但是,DisplayMetrics类包含xdpiydpi字段,这些字段可以为您提供设备在每个方向上的真实密度。然后,您可以使用这些值以编程方式绘制标尺。