如何在ArrayAdapter中设置ListItem高度等于ListView高度

时间:2014-12-08 11:52:53

标签: android listview

我想知道是否可以在ArrayAdapter的getView方法中将listitem height设置为listview height。

我该如何完成这项任务?谢谢。

1 个答案:

答案 0 :(得分:1)

Runnable fitsOnScreen = new Runnable() {
        @Override
        public void run() {

            int last = invitelist.getLastVisiblePosition();
            if(last < invitelist.getCount()-1) 
                // if(last == invitelist.getCount() - 1 && invitelist.getChildAt(last).getBottom() <= invitelist.getHeight())
            {

                invitelist.setFastScrollEnabled(true) ;
                invitelist.setFastScrollAlwaysVisible(true);

            }else {
                invitelist.setFastScrollEnabled(false);
                invitelist.setFastScrollAlwaysVisible(false);

            }

        }
    };

yourlistView.post(fitsOnScreen);

它会自动将listitem高度等于ArrayAdapter的getView方法中的listview高度。

或者您可以使用以下内容。

//package com.omareitti;

import java.util.List;
import java.util.UUID;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utils {

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }



}