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.pswp.cn/news/446811.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446811.shtml
英文地址,請注明出處:http://en.pswp.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…