繁体   English   中英

如何在ListView中为Mutil屏幕设置ImageView的宽度

[英]How to set width to ImageView in ListView for mutil screen

我有一个带有ImageView和TextView的ListView,我想将图像的宽度设置为屏幕的2/3。

如何创建自定义ImageView来做到这一点? 到目前为止,这是我尝试过的。

自订检视

public class CustomImageListView extends ImageView {
    public CustomImageListView(Context context) {
        super(context);
    }

    public CustomImageListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // Snap
        // to
        int width = MainActivity.width;
        int height = MainActivity.height;
        int w = width *2/5;
        int h = w *4/6;
        setMeasuredDimension(w, h);
        // setMeasuredDimension(ChoseImage.width, ChoseImage.height); // Snap to
        // //
        // width
    }

}

自定义View XML

<tuannt.tinmoi.custom.CustomImageListView
            android:id="@+id/ivAvater"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/nomage" />

您可以使用WeightSum = 3定义水平线性布局,并在其中放置另一个layout_weight = 1的布局,其余部分的权重= 2,因此您可以在其中放置imageView。 请参阅以下内容:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/fullscreen"
    style="@style/translucent"
    android:orientation="horizontal"
    android:weightSum="3">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_gravity="right"
        android:gravity="center"
        android:background="#88000000"
        android:id="@+id/sidebar"
        android:layout_weight="1" >

    </RelativeLayout>

<!-- other views, with a total layout_weight of 2 -->

</LinearLayout>

您无需创建自定义视图即可实现此目的。 您可以使用layout_weight属性。

这就是ListView中每个项目的布局。

item_in_listview.xml:

<?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">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>

这个问题解释了layout_weight属性。

简而言之,layout_weight指定要分配给View的布局中多少额外空间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM