我知道我应该为不同的屏幕定义不同的布局,请继续阅读。
我正在开发一个应用程序,该应用程序将运行插入 720p 或 1080p 电视的"棒上的 Android",并单独显示一些"幻灯片"。
我需要类似android:layout_width="n%"的东西。我知道我可以用LinearLayout做到这一点,但是屏幕相当复杂,不鼓励这种深度嵌套。我想坚持相对布局。
我设计了以像素为单位指定指标的布局,设计为 1080p,并将布局放在 layout-tvdpi 或 layout-xhdpi 上,希望 Android 能将其适当地缩小到 720p。它没有。所有人工制品都被夸大和重叠。
有没有办法实现我想要的?谢谢。
正如我在问题中提到的,我正在开发的应用程序将显示在 720p 或 1080p 电视上。这允许我犯以下亵渎罪:所有视图大小/填充/边距和文本大小都是在 PX 中定义的,而不是 DP,不是 SP。这样我就可以控制确切的屏幕布局。现在,与文档让我相信的相反,Android 不会调整任何在 PX 中定义大小的布局元素的大小。它只会对可绘制对象或 DP/SP 执行此操作。
因此,我不得不自己调整大小。
我在 Activity.onCreate() 中定义了 1080p 的布局,获取根布局并将其传递给:
private static final float RATIO_720_1080 = 720f/1080f;
/**
* If the screen is 720p, the resources will resize
* to fit the screen.
* @param root Root view where the resources are found.
*/
public void resizeViews(ViewGroup root) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
// only resize if 720p
if (metrics.widthPixels != 1280) return;
int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
View v = root.getChildAt(i);
// digg deep
if (v instanceof ViewGroup) {
resizeViews((ViewGroup)v);
}
// do the size
ViewGroup.LayoutParams params = v.getLayoutParams();
// keep the match_parent constants intact
if (params.height > 0) {
params.height = Math.round(params.height * RATIO_720_1080);
}
if (params.width > 0) {
params.width = Math.round(params.width * RATIO_720_1080);
}
if (params instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) params;
marginParams.setMargins(Math.round(marginParams.leftMargin * RATIO_720_1080),
Math.round(marginParams.topMargin * RATIO_720_1080),
Math.round(marginParams.rightMargin * RATIO_720_1080),
Math.round(marginParams.bottomMargin * RATIO_720_1080));
}
v.setLayoutParams(params);
v.setPadding(Math.round(v.getPaddingLeft() * RATIO_720_1080),
Math.round(v.getPaddingTop() * RATIO_720_1080),
Math.round(v.getPaddingRight() * RATIO_720_1080),
Math.round(v.getPaddingBottom() * RATIO_720_1080));
// text size
if (v instanceof TextView) {
float size = ((TextView)v).getTextSize();
size *= RATIO_720_1080;
((TextView)v).setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}
}
}
您可以使用如下所示的布局文件。请注意父布局中的 layout_sum
属性,以及每个子布局中的 layout_weight
属性。第一个孩子将占父母的70%,第二个孩子将占30%。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="70"
android:text="A"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="30"
android:text="B"/>
</LinearLayout>