0

当我浏览几个 android 示例时,我发现一些值是硬编码的,

例如:

<ImageView
    android:id="@+id/icon"
    android:layout_width="22px"
    android:layout_height="22px"
    android:layout_marginLeft="4px"
    android:layout_marginRight="10px"
    android:layout_marginTop="4px"
    android:src="@drawable/ic_launcher" >
</ImageView>

在这个图像视图值是硬编码的,对于我的自定义布局..如何避免这些硬编码?这是android中的正确方法吗?它对各种屏幕尺寸的设备有影响吗?

4

4 回答 4

2

您需要阅读一些开发者文档:

http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/practices/screens_support.html#screen-independence

不:

<ImageView
    android:id="@+id/icon"
    android:layout_width="22px"
    android:layout_height="22px"
    android:layout_marginLeft="4px"
    android:layout_marginRight="10px"
    android:layout_marginTop="4px"
    android:src="@drawable/ic_launcher" >
</ImageView>

以上将无法很好地跨屏幕缩放

是的:

<ImageView
    android:id="@+id/icon"
    android:layout_width="22dip"
    android:layout_height="22dip"
    android:src="@drawable/ic_launcher" >
</ImageView>

以上将每个设备“独立”缩放其像素

或者

<ImageView
    android:id="@+id/icon"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher" >
</ImageView>

以上将相对于屏幕尺寸绘制自身

或者

<ImageView
    android:id="@+id/icon"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="22dip"
    android:src="@drawable/ic_launcher" >
</ImageView>

以上将相对于屏幕大小和屏幕上的其他视图绘制自身

或者

ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        imageView.setImageDrawable(R.drawable.background);

        layout.addView(imageView);

以上是以编程方式创建的

于 2012-04-21T14:57:15.973 回答
1

最好使用“dp”单位而不是“px”。

DP 会随屏幕大小调整,而不是 PX。

请参阅http://developer.android.com/guide/practices/screens_support.html

于 2012-04-21T14:55:35.020 回答
0

在这个图像视图值是硬编码的,对于我的自定义布局..如何避免这些硬编码?

首先,通常不应将px其用作尺寸,因为硬件像素的大小会根据屏幕密度而变化。使用dp或其他度量单位(例如,mm)。

其次,如果您有计划重用的维度,或者您只是希望在一个地方收集它们的值,请使用维度资源。然后,您的布局将引用这些资源(例如,android:layout_marginTop="@dimen/something")。

于 2012-04-21T14:56:41.373 回答
0

值应该在“dp”或“dpi”中,不同的android设备会相应地调整。

这将对您有所帮助:http: //developer.android.com/guide/practices/screens_support.html

于 2012-04-21T14:56:55.640 回答