我将listView放在一个popupWindow中,当它有很多项时,popupWindow超过了屏幕尺寸,所以我想限制listView的最大高度(或最大项,如果超过则显示滚动条),谢谢大家
发布于 2016-06-24 12:23:03
试试这个,可能对你有帮助。
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < 5; i++) //here you can set 5 row at a time if row excceded the scroll automatically available
{
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup) {
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
你可以像这样使用
YourAdapter mYoursAdapter = new YourAdapter();
mListview.setAdapter(mYoursAdapter);
setListViewHeightBasedOnChildren(mListview);
发布于 2016-06-24 12:46:11
在project.Try中创建一个类AppUtil,如下所示:
public class AppUtil{
public static void setListViewHeightBasedOnChildren(ListView listView) {
if (listView == null) {
return;
}
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup) {
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
要在您的活动或片段中调用上面的方法,您可以像这样进行:
public class MedicalReportsFragment extends Fragment {
@Bind(R.id.lv_investigative_report)
ListView investigativeReportLV;
private MedicalReportsAdapter mMedicalReportsAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mMedicalReportsAdapter = new MedicalReportsAdapter(getActivity(), mMedicalReportOverviews,true);
investigativeReportLV.setAdapter(mMedicalReportsAdapter);
AppUtil.setListViewHeightBasedOnChildren(investigativeReportLV);
}
}
发布于 2018-06-04 16:04:47
我认为你可以在你的layout.xml中尝试这个技巧:
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp" />
<LinearLayout
android:id="@+id/layout_bottom_button"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="-40dp" />
事实上,marginBottom将为ListView下面的布局保留40dp,这样你的ListView就不会像以前那样覆盖整个屏幕。
https://stackoverflow.com/questions/38005517
复制相似问题