Android:查找ListView的项目渲染高度

标签 android listview

有没有什么方法可以找到当前显示在列表中的 ListView 项目的高度,而无需自己在布局 xml 文件中进行设置?

我试过了

View listItem = listAdapter.getView(currentIndex, null, listView);
listItem.measure(MeasureSpec.EXACTLY, MeasureSpec.UNSPECIFIED);
int itemHeight = listItem.getMeasuredHeight();

虽然它最初工作正常,但它决定在启动新的模拟器 session 后的 measure() 调用期间抛出空指针异常。

我正在尝试做的是让一个短列表中的项目(只有 2 或 3 个完整的项目可见)在程序选择时居中。

最佳答案

这对我有用:

public static int getItemViewHeight(Context context, Adapter adapter, int index) {
    FrameLayout fakeParent = new FrameLayout(context);
    View view = adapter.getView(index, null, fakeParent);
    view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    return view.getMeasuredHeight();
}

关于Android:查找ListView的项目渲染高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7933823/

相关文章:

javascript - Cordova PhoneGap 从 2.2.0 升级到 5.1.1

php - 在 PHP/MySQL/Android 上比较单个用户位置与多个用户位置的方法

android - 如何在运行时在 ICS 中添加/删除菜单项?

android - 如何在 jetpack compose 中使用 retrofit API 创建 ListView / GridView /回收器 View

java - 我有一个 firebase 数据库,我想从中访问一些嵌套节点,然后将数据列表添加到该特定节点

android - 为什么需要更改协程中的调度程序?

android - getView 中的自定义 ArrayAdapter setBackground

java - 使用 EndlessRecyclerOnScrollListener 的 Asynctask 的无尽 RecyclerView

xaml - 如何删除 ListView GroupStyle 标题分隔线?

android - Android ListView 中未显示顶部和底部分隔符