wrap_content用于listview的宽度

Gra*_*tzi 16 android listview width

有没有办法让ListView的with等于最长的行?为ListView的宽度设置wrap_content无效.ListView水平覆盖整个屏幕.

这是活动布局

<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" />
Run Code Online (Sandbox Code Playgroud)

这是行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>
Run Code Online (Sandbox Code Playgroud)

谢谢Gratzi

sat*_*ine 35

有时候,你知道总会有数量有限的项目,可能是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;
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它(注意我在宽度上添加了一些额外的空间以防万一):

listView.getLayoutParams().width = getWidestView(mContext, adapter)*1.05;
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案在我拥有的基于片段的应用程序中完美运行.在包含15个项目的ListView上,System.currentTimeMillis()显示ListView可以在6毫秒内调整为最佳宽度. (2认同)
  • Android应该这样做并将其作为开发人员的选项.实际上我认为选项是"wrap_content",但实际上并非如此. (2认同)

Com*_*are 17

有没有办法让ListView的with等于最长的行?

不,部分是因为我们无法知道最长的行是什么.

比方说,你附加ListAdapterListView,其中getCount()ListAdapter回报值1,234,567.要确定最长行的宽度,我们必须创建每一行并检查其宽度.这将需要数小时,用户在这些时间内不会感到高兴.