ListView项目高度始终相同(和错误)

时间:2015-07-31 13:32:39

标签: android listview

我尝试调整ListView的大小以显示所有项目。

final ListAdapter adapter = timeline.getAdapter();
int totalHeight = 0;
final int desiredWidth = View.MeasureSpec.makeMeasureSpec(timeline.getWidth(), View.MeasureSpec.AT_MOST);
for (int i = 0; i < adapter.getCount(); i++) {
    final View listItem = adapter.getView(i, null, timeline);
    listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
    Log.v(TAG, "Item size = " + listItem.getMeasuredHeight());  // Always 38
    totalHeight += listItem.getMeasuredHeight();
}
final ViewGroup.LayoutParams params = timeline.getLayoutParams();
params.height = totalHeight;
timeline.setLayoutParams(params);
timeline.requestLayout();

为什么listItem.getMeasuredHeight()总是38,忽略项目的XML布局中指定的android:layout_height

getView()方法非常标准:

@Override
public View getView(final int position, View view, final ViewGroup parent) {
    final ViewHolder holder;

    if (view == null) {
        final LayoutInflater li = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = li.inflate(R.layout.timeline_item, parent, false);

        holder = new ViewHolder(view);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    final ActivityLogItem log = (ActivityLogItem) getItem(position);
    holder.time.setText(format.print(log.getRecordedTime().withZone(DateTimeZone.getDefault())));
    holder.time.setTextColor(log.isImportant() ? view.getResources().getColor(R.color.orange) : Color.WHITE);
    holder.event.setText(log.getLocalizedType(view.getResources()));
    holder.event.setTextColor(log.isImportant() ? view.getResources().getColor(R.color.orange) : Color.BLACK);

    return view;
}

0 个答案:

没有答案