【发布时间】:2016-11-22 23:24:58
【问题描述】:
(附在问题底部的图片)
我有这个布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mainLayout">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:paddingTop="10dp"
android:layout_height="match_parent"
android:id="@+id/viewsLayout"
android:layout_weight="1.0">
</LinearLayout>
</LinearLayout>
我想将球的 3x3 图像视图添加到内部线性布局“viewsLayout”中,因此我将在其适当的类中这样做:
LinearLayout main = (LinearLayout) findViewById(R.id.viewsLayout);
main.setWeightSum(3.0f);
for (int i = 0; i < 3; ++i) {
LinearLayout currentRow = new LinearLayout(this);
currentRow.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
params.weight = 1.0f;
currentRow.setLayoutParams(params);
for (int j = 0; j < 3; ++j) {
ImageView viewOne = new ImageView(this);
viewOne.setBackgroundResource(R.drawable.ball);
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
viewOne.setLayoutParams(params);
viewOne.setScaleType(ImageView.ScaleType.FIT_CENTER);
viewOne.setAdjustViewBounds(true);
currentRow.addView(viewOne);
}
main.addView(currentRow);
}
问题是在横向模式下,球变成椭圆(太拉伸),正如您在附图中看到的那样。
我看到这个问题已经被问过了,不建议避免使用横向模式。 (我添加了一张图片,以便搜索者轻松找到。)我看到解决方案是为横向模式创建一个新布局,但我有很多布局,因此为横向模式为每个布局创建另一个布局可能很可怕。有更好的解决方案吗?如果不是,我是否必须通过 dp 而不是 MATCH_PARENT 设置 linearLayout\ImageView 的宽度?
【问题讨论】:
-
您正在设置 ImageView 的背景而不是资源,因此您的缩放/adjustViewbounds 不会影响它。请改用
viewOne.setImageResource(R.drawable.ball);。 -
实际上,这仍然不是您想要的。如果你想让 3x3 像这样适合中心,你将不得不为景观使用不同的通货膨胀代码,以保持它们的正确加权
-
哇设置了图片资源后看起来棒极了!但为什么你认为这不是我想要的?也许我的解释不好,或者它可能有我现在没想到的行为?现在看起来更完美了! :)
-
如何将您的评论设置为我问题的答案?
标签: java android imageview android-linearlayout landscape