Android中重温自定义控件03----布局测量的使用,自定义ListView

本文介绍了解决ListView在嵌套于ScrollView时只显示一行的问题。通过自定义NoScrollListView,重写onMeasure方法,使得ListView能完全展开并显示所有条目。此方法适用于希望在ScrollView中完全展示ListView内容的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当 ListView 被嵌套在 ScrollView 等滑动控件中,只能展示一行,这时候就需要自定义了
 代码如下:

布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zhh.android.MainActivity"
    android:orientation="vertical"
    >
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.zhh.android.NoScrollListView
            android:id="@+id/noScrollListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </com.zhh.android.NoScrollListView>

    </ScrollView>



</LinearLayout>

自定义控件 NoScrollListView

/**
 *
 * 自定义 ListView
 * 当在滚动布局中,listView 显示一行,通过测量listView条目加起来的总高度
 * 使 listView 全部展开
 */

public class NoScrollListView extends ListView {

    public NoScrollListView(Context context) {
        super(context);
    }

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

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

    // 重写onMeasure方法,以便自行设定视图的高度
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        // 将高度设为最大值,即所有项加起来的总高度
        // AT_MOST 测量模式,对应的就是 MATCH_PARENT 与父布局的尺寸一样,就是listView的总高度
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

源码下载:
TestCustom ---- app3
https://download.youkuaiyun.com/download/zhaihaohao1/11224806

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值