【发布时间】:2016-03-29 13:44:31
【问题描述】:
我有一个像这样的 ImageButton:
<ImageButton
android:background="@drawable/ctg_a"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:id="@+id/cmdCategoryA" />
我的布局在一个线性布局内有多个这样的 ImageButtons(嵌套在一个滚动视图内)。按钮应占其宽度的 100% 可用空间,并使用匹配的高度,因此图像的比例 (5:3) 不会改变。
使用我的代码,我让图像在宽度上填满整个页面,但在高度上,图像使用其原始尺寸,该尺寸太大且与比例不匹配。
因此,目前,图像大约是 5:8 而不是 5:3。如何降低高度?
编辑:它可能与上下文有关吗?这是我的活动代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.mjz.test.MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:background="@drawable/ctg_a"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:id="@+id/cmdCategoryA"
android:scaleType="centerCrop" />
</LinearLayout>
</ScrollView>
</LinearLayout>
我采用了另一种方法来清除 xml,并动态添加按钮。我的代码:
ImageButton cmdCategoryA;
LinearLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout)findViewById(R.id.categories_layout);
setTitle("Kategorien");
Configuration configuration = this.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp;
cmdCategoryA = new ImageButton(getApplicationContext());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity= Gravity.CENTER;
layoutParams.width=screenWidthDp;
layoutParams.height=(screenWidthDp/5)*3;
cmdCategoryA.setLayoutParams(layoutParams);
cmdCategoryA.setBackground(getDrawable(R.drawable.ctg_a));
mainLayout.addView(cmdCategoryA);
}
这种工作,只是图像不是全宽,而是屏幕的~1/3。 screenWidthDp 返回 360,这对于我的 nexus 5 是正确的。
我必须在某处添加类型 (dp/px/...) 吗?
【问题讨论】:
-
你想动态降低高度吗?
-
@saran 不需要,活动不是动态生成的,所以我需要的一切在设计时都已经可用。但是当我改变 scaleType 时,它并没有改变任何东西。
-
所以你想减少图像视图的多余高度..以保持纵横比..?
-
@saran 确切地说,在 xml 中
-
通常使用滚动视图,如果图像尺寸较大,它们往往会根据其原始尺寸占据完整的空间。要解决此问题,您应该使用尺寸较小的图像