android - 用于 ListView 宽度的 wrap_content

标签 android listview width

有没有办法让 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/

相关文章:

Safari 和 IE 8 的 css 样式问题

python - 是否可以设置小部件的宽度而不修复它?

android应用程序直接使用android设备中保存的帐户凭据登录

java - Build.version < 16 的 setBackground 和 getBackground 方法

android - 从 ListView 中删除 SQLite 数据

android - 为什么 Android 中的项目高度不包裹内容?

c# - 通过x :bind in UWP绑定(bind)数据到ListView

javascript - 使用JS在4k显示器上查找屏幕尺寸

安卓模拟器: Changing network bars

Android 的主要 Activity 仍然是旧的。如何设置新的?