当我浏览几个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中的正确方法吗?它对各种屏幕大小的设备有什么影响吗?
答案 0 :(得分:2)
您需要阅读一些开发人员文档:
http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/practices/screens_support.html#screen-independence
NO:
<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);
以上是以编程方式创建的
答案 1 :(得分:1)
最好使用“dp”单位而不是“px”。
DP将根据屏幕尺寸进行调整,而不是PX。
请参阅http://developer.android.com/guide/practices/screens_support.html
答案 2 :(得分:0)
在这个图像中,视图值是硬编码的,对于我的自定义布局..如何避免这些类型的硬编码?
首先,通常不应将px
用作维度,因为硬件像素的大小可能会因屏幕密度而异。使用dp
或其他计量单位(例如mm
)。
其次,如果您计划重复使用维度,或者只是想在一个地方收集其值,请使用dimension resources。然后,您的布局将引用这些资源(例如android:layout_marginTop="@dimen/something"
)。
答案 3 :(得分:0)
值应该是“dp”或“dpi”,不同的Android设备会相应调整。
这将对您有所帮助:http://developer.android.com/guide/practices/screens_support.html