我有一个listview,我需要设置高度,但在字符串中我使用\n
来创建换行符,当这些在listview中时,它会与视图的最终高度混淆,使底部的一个或两个项目的文本从视图中被切断。
基本上,下面的代码不适用于包含不同高度行的列表视图。它只会使其高度偏离第一行的高度,再乘以行数。
以下是我用来设置listview高度的标准代码:
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
答案 0 :(得分:1)
由于您已经填充了所有视图,因此应该使用LinearLayout替换ListView。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- top -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
<!-- fake listview -->
<LinearLayout
android:id="@+id/ll_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
<!-- bottom -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
</LinearLayout>
</ScrollView>
代码:
LinearLayout llList = (LinearLayout)findViewById(R.id.ll_list);
LayoutInflater inflater = LayoutInflater.from(this);
String[] data = new String[] {"1","2","3"};
for(int i = 0 ; i < data.length ; i++)
{
View childView = inflater.inflate(R.layout.spinner_item, null); //same layout you gave to the adapter
TextView tv = (TextView)childView.findViewById(R.id.tv_name);
tv.setText(data[i]);
llList.addView(inflater.inflate(R.id.sepatator, null)); // if you want a separator can be a simple view with a line and margins
llList.addView(childView);
}
对于分隔符,您可以使用:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#555" >
</View>
</LinearLayout>