我有一个列表视图,我需要设置它的高度,但是在字符串中,我使用\n
创建换行符,当这些字符串在列表视图中时,它会扰乱视图的最终高度,使底部一两个项中的文本与视图被切断。
基本上,下面的代码并不适用于包含不同高度行的列表视图。它似乎只将其高度与第一行的高度相乘,乘以有行的数量。
下面是我用来设置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);
}
发布于 2014-08-01 08:42:49
由于您已经填充了所有视图,所以应该用一个ListView替换LinearLayout。
<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>
https://stackoverflow.com/questions/25084247
复制相似问题