vod*_*ong 1 android listview textview
我正在使用这种方法来计算列表视图的高度,但它并不完全符合我的要求。因为,当内容很长时,我的列表视图有一个 TextView 可能是多行的。当TextView为oneline时是对的,但是当它有2行时,它的高度是错误的。谢谢!
代码
public static boolean setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
// Get total height of all items.
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(numberOfItems - 1);
// Set list height.
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/red"
android:orientation="vertical">
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/border_margin"
android:text="name"
android:paddingLeft="200dp"
android:textColor="@color/header_lounge"
android:textSize="@dimen/text_normal"
android:textStyle="bold" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
ListView当TextView变为multiline时,所有可用于计算基于子项的高度的方法都失败了。
我也遇到了同样的问题,经过多次尝试,我找到了这个问题的解决方案。
主要概念是,如果您设置了您所拥有的确切行数,
TextView那么将正确计算高度,即您需要如何执行以下操作,
textView.setLines(numberOfLines)
Run Code Online (Sandbox Code Playgroud)
有了这个,您的问题将得到解决。
现在下一个问题是如何知道 TextView 将动态拥有的确切行数。
我会说这完全取决于您的情况。就我而言,我所做的是,
textView.setText(fullString);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int screenWidth = display.getWidth(); // Get full screen width
int eightyPercent = (screenWidth * 80) / 100; // Calculate 80% of it
// as my adapter was having almost 80% of the whole screen width
float textWidth = textView.getPaint().measureText(fullString);
// this method will give you the total width required to display total String
int numberOfLines = ((int) textWidth/eightyPercent) + 1;
// calculate number of lines it might take
textView.setLines(numberOfLines);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1146 次 |
| 最近记录: |