【问题标题】:Get size of UI before actually creating one?在实际创建 UI 之前获取 UI 的大小?
【发布时间】:2014-07-09 21:30:47
【问题描述】:
我正在开发一个主要由代码而非 xml 驱动的 Android 应用程序。
ListView 的适配器想知道项目的高度。但这又可能取决于项目中 UI 元素的大小。例如,如果项目包含一个复选框,则复选框的大小可能会影响列表项的布局,这反过来可能会改变高度,具体取决于是否需要换行。
问题——有没有一种方法可以在不实际创建的情况下获取 Android UI 元素的大小?类似于使用 Paint 或 TextPaint 对象在绘制文本之前获取文本大小的方式。
【问题讨论】:
标签:
android
user-interface
【解决方案1】:
不创建它?不,但您可以使用 MeasureSpec 类并在创建视图后手动测量它。为什么你需要知道确切的尺寸?您不能将 LayoutParams 设置为MATCH_PARENT(宽度)和WRAP_CONTENT(高度)吗?
也就是说,如果您确实需要知道,您可以使用 ListView 的宽度作为宽度 MeasureSpec,然后使用 UNSPECIFIED 作为高度 MeasureSpec:
// Tell the View it should be exactly as wide as the ListView...
int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth, MeasureSpec.EXACTLY);
// ... and as tall as it wants to be ...
int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
// ... measure it with these constraints ...
item.measure(widthSpec, heightSpec);
// ... and retrieve the measured height.
int itemHeight = item.getMeasuredHeight();