Wrap_content для ширины списка
Есть ли способ иметь ListView с равным самой длинной строке? Установка параметра wrap_content для ширины ListView не влияет. 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" />
и это строка 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>
Спасибо,
Gratzi
Ответы
Ответ 1
Есть ли способ иметь ListView с равным самой длинной строке?
Нет, отчасти потому, что мы не знаем, что такое самая длинная строка.
Скажем, что вы прикрепляете ListAdapter
к ListView
, где getCount()
на ListAdapter
возвращает значение 1,234,567
. Чтобы определить ширину самой длинной строки, нам нужно было бы создать каждую строку и изучить ее ширину. Это займет несколько часов, и пользователь не будет счастлив в те часы.
Ответ 2
Иногда вы знаете, что всегда будет ограниченное количество элементов, возможно, 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;