Android 动态计算ListView的高度

目录

  • 一、简介
  • 二、效果图
  • 三、代码实现

一、简介


在Android开发的过程中有的时候我们需要手动计算ListView的高度,比如说,ScrollView中嵌套ListView的时候,我们就需要手动精确计算ListView的高度了。

如果ListView的Item高度是固定的话还好计算一些,我们可以直接使用Item的条数 * Item的固定高度来计算,但是如果Item的高度随着内容的变化而变化,那么该如何计算呢?

下面我们就开始说说如何精确计算ListView的高度吧。

二、效果图


先看下界面效果:
在这里插入图片描述
从效果图中我们可以看到:

红色背景的是Item,蓝色背景的是ListView的dividerHeight的高度,同时我们也设置了ListView的paddingTop和paddingBottom值。

三、代码实现


下面我们就直接上代码:

1、Item的布局文件list_item.xml

<?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"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/txt_item_info"android:gravity="center"android:textColor="#ffffff"android:padding="20dp"android:textSize="18sp"android:lineSpacingExtra="10dp"android:text="测试一"android:background="@color/colorAccent"/></LinearLayout>

Item布局文件中就定义了一个TextView,TextView的高度随着内容的变化而变化。

2、ListView界面的布局文件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"android:orientation="vertical"tools:context=".MainActivity"><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:gravity="center"android:background="#30B8E3"android:textColor="#ffffff"android:textSize="18sp"android:text="动态计算ListView高度"/><Buttonandroid:layout_width="match_parent"android:layout_height="50dp"android:id="@+id/btn_add"android:text="添加Item"/><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><ListViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/listview"android:divider="@color/colorPrimaryDark"android:dividerHeight="10dp"android:paddingTop="10dp"android:paddingBottom="10dp"android:cacheColorHint="#00000000"android:listSelector="#00000000"android:background="#ffffff"android:orientation="vertical"></ListView><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:background="#30B8E3"android:textColor="#ffffff"android:gravity="center"android:text="检测ListView高度是否精确"/></LinearLayout></ScrollView></LinearLayout>

这里我们设置了ListView的dividerHeight、paddingTop、paddingBottom。


3、ListView高度计算


布局文件准备好后,我们就来看下最关键的地方,动态计算ListView的高度,这里我们只贴出计算ListView高度的代码:

	public void setListViewHeight(ListView listview){ListAdapter adapter = listview.getAdapter();if(adapter == null){return;}int totalHeight = 0;// 计算ListView的宽度int listViewWidth = ((Activity)mContext).getWindowManager().getDefaultDisplay().getWidth();int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth, View.MeasureSpec.AT_MOST);for(int i=0;i<adapter.getCount();i++){View view = adapter.getView(i, null, listview);// 这里的第一个参数必须使用widthSpec,// 如果使用0的话,无法计算出随内容变化而变化的Item的真正高度值view.measure(widthSpec, 0);totalHeight += view.getMeasuredHeight();}int dividerHeight = listview.getDividerHeight() * (adapter.getCount() - 1);totalHeight += dividerHeight;Log.i("ListViewHeight", "ListView DividerHeight : " + dividerHeight);int paddingHeight = listview.getPaddingTop() + listview.getPaddingBottom();totalHeight += paddingHeight;Log.i("ListViewHeight", "ListView PaddingHeight : " + paddingHeight);Log.i("ListViewHeight", "ListView TotalHeight : " + totalHeight);ViewGroup.LayoutParams layoutParams = listview.getLayoutParams();layoutParams.height = totalHeight;listview.setLayoutParams(layoutParams);this.refresh();}

其中,最关键的地方就是下面这几行代码:

	// 计算ListView的宽度int listViewWidth = ((Activity)mContext).getWindowManager().getDefaultDisplay().getWidth();int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth, View.MeasureSpec.AT_MOST);// 这里的第一个参数必须使用widthSpec,// 如果使用0的话,无法计算出随内容变化而变化的Item的真正高度值view.measure(widthSpec, 0);

完整代码已上传至Github:动态计算ListView高度

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/446811.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

DjangoRestFramework(drf实现五个接口)

安装&#xff1a;pip install djangorestframework 在使用drf之前&#xff0c;先 使用原生Django实现5个接口 models.py from django.db import modelsclass Book(models.Model):namemodels.CharField(max_length53)pricemodels.IntegerField() views.py from app01 impor…

linux使用共享内存进行进程通信

一、什么是共享内存 共享内存就是允许两个不相关的进程访问同一个逻辑内存。共享内存是在两个正在运行的进程之间共享和传递数据的一种非常有效的方式。不同进程之间共享的内存通常为同一段物理内存。使用共享内存进行通信的进程都需要同一段共享内存连接到它们自己的地址空间…

安卓TextView文本框与自定义边框

常用属性 自定义边框 基本使用 <?xml version"1.0" encoding"utf-8"?> <shape xmlns:android"http://schemas.android.com/apk/res/android"android:shape"rectangle矩形/ring圆环/oval椭圆/line直线"当为圆环时android:s…

Android RecyclerView实现九宫格效果

RecyclerView更加优化的复用机制和方便实现UI效果&#xff0c;几乎替代Listview和GridView的使用。但是分割线的实现&#xff0c;需要自己继承ItemDecoration来绘制。 完整代码已上传至Github&#xff1a;RecyclerView实现九宫格效果 效果图 item的布局文件 <?xml versi…

如何读取指针指向的地址空间呢?

方法 使用%p 接收指针返回的地址空间 代码 #include <stdio.h> #include <stdlib.h>int main() {int a 100;int *a_p &a;printf("%p\n",&a);//输出&#xff1a;002AF744 输出的是a变量的地址printf("%p\n",a_p);//输出&#xff1…

科学究研明表,汉字序顺并不一定影阅响读

有个很有意思的现象&#xff1a; 不信你就来试试 中文打乱小工具 github地址&#xff1a;在线打乱文字顺序

安卓EditText

常用属性 android:textAllCaps"false"去除大写状态 inputType 常用 textpassword密码 number数字 phone拨号键盘 设置光标位置 editText.setSelection(2);从1开始 editText.setSelection(1,3);从1开始,1–3中间部分,一个范围

完善博文 共享内存一写多读无锁实现的代码逻辑部分

使用共享内存(内存映射)实现发布订阅模式 多进程实现PubSub发布订阅模式&#xff0c;从而实现进程间的通信。通信方式可以是TCP/UDP&#xff0c;管道Pipe/消息队列&#xff0c;共享内存shared memory等等。其中TCP/UDP的方式是可以用作局域网以及跨平台的通信&#xff0c;Pipe…

想对你说的话,就在这里!

甜(Tu)言(Wei)蜜(Qing)语(Hua)最近在github上看到了一个朋友开发的 土味情话在线生成器 &#xff0c;感觉还不错&#xff0c;在这里推荐一下。 github地址&#xff1a;在线生成土味情话

linux读写文件 简单版

代码 //write void write_file(const std::string file_name){FILE *fp nullptr;fp fopen(file_name.c_str(),"w");fprintf(fp,"This is testing for mutex\n");fclose(fp); } //read void read_file(const std::string file_name){std::ifstream fp(fi…

具有中国风的传统颜色(炫酷)

一个小小的中国风的传统颜色&#xff0c;你觉得应该是什么样子的呢&#xff1f; 看了下面这个&#xff0c;我一个搞移动开发的都想去搞前端开发了。 废话不多说了&#xff0c;直接看效果&#xff1a; 访问地址&#xff1a;中国传统颜色手册 github地址&#xff1a;Chinese…

Android Studio安装问题及填坑

安装过程 安装Android Studio 其他问题 1.Android Studio出现Error:Unable to tunnel through proxy. Proxy returns “HTTP/1.1 400 Bad Request” 2.Could not resolve all artifacts for configuration :classpath 3.!No cached version of com.android.tools.build:gr…

Linux strtol将十六进制转化为十进制

代码 #include <iostream> #include "crypto_util.h"int get_file(const std::string file_name){size_t get_file_id 0;std::cout << hsm::common::get_md5_digest_hex(file_name) << std::endl;get_file_id strtol(reinterpret_cast<const…

Android WebView使用攻略

目录前言一、简介二、作用三、使用介绍1、Webview类常用方法1.1、加载url1.2、WebView的状态1.3、关于前进 / 后退网页1.4、清除缓存数据2、常用工具类2.1、WebSettings类2.2、WebViewClient类2.3、WebChromeClient类3、注意事项&#xff1a;如何避免WebView内存泄露&#xff1…

C++If与Switch语句

IF if语句不加括号就只是一个语句 举例: int a5,b2; if(a)//按逻辑值来理解,0为假,其他为真,这里等价于a!0—>a为真时 ab; else ba; 计算三角形面积代码 #include<iostream> #include<cmath>//数学公式库 #include<iomanip> //格式控制 using namesp…

linux fork多进程 demo

注释 使用系统调用fork()创建三个子进程&#xff1b;各个子进程显示和输出一些提示信息和自己的进程标识符&#xff1b;父进程显示自己的进程ID和一些提示信息&#xff0c;然后调用waitpid()等待多个子进程结束&#xff0c;并在子进程结束后显示输出提示信息表示程序结束。 代…

Android WebView 与 JS 交互

目录二、具体分析2.1 Android通过WebView调用 JS 代码方式1&#xff1a;通过WebView的loadUrl()方式2&#xff1a;通过WebView的evaluateJavascript()方法对比使用建议2.2、JS通过WebView调用 Android 代码2.2.1、方法分析方式1&#xff1a;通过 WebView的addJavascriptInterfa…

关于锁的注意事项

文件锁 Linux 提供了 fcntl 系统调用&#xff0c;可以锁定文件但是文件锁是和进程相关联的&#xff0c;一个进程中的多个线程/协程对同一个文件进行的锁操作会互相覆盖掉&#xff0c;从而无效。fcntl 创建的锁是建议性锁&#xff0c;只有写入的进程和读取的进程都遵循建议才有效…

安卓实现登录与注册界面

使用Intent与Bundle传递数据 登录界面login.xml 1.使用Relativelayout相对布局 <?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"mat…

Android Button字母自动全部大写的问题

两种解决方案&#xff1a; 方法一&#xff1a; 在 xml 布局中设置属性 android:textAllCaps"false" <Buttonandroid:layout_width"wrap_content"android:layout_height"match_parent"android:text"添加动作组"android:textAllCap…