从布局中根据屏幕设置ImageView的高度

4
我正在制作布局并使用“layout_weight”和“weight_sum”。我将线性布局的方向设置为水平,以便能够将ImageView的宽度设置为屏幕的1/3。但是我不知道如何将ImageView的高度设置为屏幕的1/3。
请帮助我从布局xml中设置ImageView的高度为屏幕的1/3。
<?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="horizontal" 
    android:weightSum="1">

    <ImageView
    android:id="@+id/savedImageView"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:background="@drawable/background" />

</LinearLayout>

提前致谢

3个回答

14

使用此代码:

int displayWidth = getWindowManager().getDefaultDisplay().getHeight();

ImageView imageView = (ImageView)findViewById(R.id.image);

imageView.getLayoutParams().height = displayWidth / 3;

我想从XML布局中做同样的事情。那么我该怎么做? - user2601652
1
似乎工作正常,除了一个情况,如果图像高度小于屏幕高度的1/3,则不会被缩放到屏幕高度的1/3。编辑:为了使其正常工作,我们需要在ImageView的xml定义中设置android:scaleType="centerCrop" - Marek

11

如果您像这样放置一个外部水平线性布局,那么您的ImageView将同时具有1/3屏幕宽度和1/3屏幕高度。内部线性布局是垂直的,因此如果您只需要1/3屏幕高度,可以直接使用它。

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/out"
    android:weightSum="3"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:weightSum="3" >

        <ImageView
            android:id="@+id/savedImageView"
            android:layout_width="fill_parent"
            android:layout_height="0px"
            android:layout_weight="1"
            android:background="@drawable/yourdrawablename" />
    </LinearLayout>

</LinearLayout>

我使用它来设置ImageView的1/3,但是在LinearLayout内部覆盖整个屏幕的高度。我希望它也应该是1/3。 - user2601652
权重既可以用作水平方向也可以用作垂直方向,所以你不能像那样改变线性布局的大小设置。你要求的是图像视图,这就是实现它的方法。如果你希望外层布局也有精确的结果,你必须通过编程来实现。 - canova

-2

你需要类似这样的东西吗?还是请详细说明你的问题,这样我才能帮助你。

<?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="horizontal" 
    android:weightSum="1">

    <ImageView
        android:id="@+id/savedImageView"
        android:layout_width="0dip"
        android:layout_height="414dp"
        android:layout_weight="0.52"
        android:background="@drawable/ic_launcher" />

</LinearLayout>

从这段代码中可以设置宽度,但无法设置高度。我想要从weightsum和layout_weight属性来设置高度和宽度。 - user2601652
请上传您想要显示在布局中的图像,我不理解您的问题。 - Developer
我的意思是,我在问题中粘贴了上面的代码,它根据屏幕宽度设置了ImageView的宽度,但我想将高度和宽度都设置为屏幕的1/3。我成功地设置了宽度或高度,但无法从布局属性中同时设置宽度和高度。 - user2601652
请检查我的答案,它处理了宽度和高度。 - canova

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接