有没有办法让 ListView 的 with 等于最长的行?为 ListView 的宽度设置 wrap_content 无效。 ListView 水平覆盖整个屏幕。
这是 Activity 布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/country_picker_bg" />
这是 xml 行
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginBottom="@dimen/padding"
android:padding="@dimen/padding"
android:background="@drawable/white_round_rect" >
<TextView android:id="@+id/title"
style="@style/GreyTextView"
android:layout_marginLeft="@dimen/padding"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/orange_arrow_selector"/>
</LinearLayout>
谢谢你, 格拉茨
最佳答案
有时,您知道项目的数量总是有限的,可能是 5 个,也可能是 40 个。在那些时候,您仍然想使用 ListView 并且仍然想包装内容。
当时有这种方法:
/**
* Computes the widest view in an adapter, best used when you need to wrap_content on a ListView, please be careful
* and don't use it on an adapter that is extremely numerous in items or it will take a long time.
*
* @param context Some context
* @param adapter The adapter to process
* @return The pixel width of the widest View
*/
public static int getWidestView(Context context, Adapter adapter) {
int maxWidth = 0;
View view = null;
FrameLayout fakeParent = new FrameLayout(context);
for (int i=0, count=adapter.getCount(); i<count; i++) {
view = adapter.getView(i, view, fakeParent);
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = view.getMeasuredWidth();
if (width > maxWidth) {
maxWidth = width;
}
}
return maxWidth;
}
像这样使用它(注意我在宽度上添加了一些额外的空间以防万一):
listView.getLayoutParams().width = getWidestView(mContext, adapter)*1.05;
关于android - 用于 ListView 宽度的 wrap_content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6547154/