动态更改Listview的高度Android

时间:2012-12-24 11:36:11

标签: android android-layout

我的XML文件格式如下:

 LinearLayout 

     ScrollView

         RelativeLayout

             LinearLayout

             <ListView
               android:id="@android:id/list"
               android:layout_width="match_parent"
               android:layout_height="fill_parent"
               android:layout_margin="5dip"
               android:layout_weight="30" >
             </ListView>

             LinearLayout

这是我的BaseAdapter类

public class APIQuickCheckoutProductProvider extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;

public APIQuickCheckoutProductProvider(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data = d;
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.product_item, null);

    TextView brand = (TextView) vi.findViewById(R.id.brands); 
    TextView quantity_name = (TextView) vi.findViewById(R.id.quantity_name); 

    TextView price = (TextView) vi.findViewById(R.id.price); 

    HashMap<String, String> product = new HashMap<String, String>();
    product = data.get(position);

    // Setting all values in listview
    brand.setText(product.get(APIQuickCheckout.KEY_BRAND));
    quantity_name.setText(product.get(APIQuickCheckout.KEY_QUANTITY_NAME));
    price.setText(product.get(APIQuickCheckout.KEY_PRICE));

    return vi;
}
}

这是我设置适配器的主要类:

adapter = new APIQuickCheckoutProductProvider(APIQuickCheckout.this, productList);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();

最后,这是我设置为listview的每一行

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dip"
    android:layout_weight="7"
    android:weightSum="6" >

    <TextView
        android:id="@+id/brands"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="3" />

    <TextView
        android:id="@+id/quantity_name"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="3" />
  </LinearLayout>

  <LinearLayout
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dip"
    android:layout_weight="2"
    android:weightSum="6" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="3" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="3" />
   </LinearLayout>

 </LinearLayout>

然而,当我尝试上面提到的代码时,它会显示第一个产品,而我只能看到第二个产品的顶部。从那时起我就什么都看不见了。那么,当我添加新产品时,如何动态更改ListView的高度?为了显示所有这些。

8 个答案:

答案 0 :(得分:16)

如果要动态更改列表视图的高度,可以使用

list.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));

答案 1 :(得分:3)

import android.view.ViewGroup.LayoutParams;

 ListView mListView = (ListView)   findViewById(R.id.listviewid);
 LayoutParams list = (LayoutParams) mListView.getLayoutParams();
   list.height = set the height acc to you;//like int  200
   mListView.setLayoutParams(list);

答案 2 :(得分:2)

试试这个答案,

public static void setListViewHeightBasedOnChildren(final ListView listView) {
    listView.post(new Runnable() {
        @Override
        public void run() {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }
            int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
            int listWidth = listView.getMeasuredWidth();
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(
                        View.MeasureSpec.makeMeasureSpec(listWidth, View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));


                totalHeight += listItem.getMeasuredHeight();
                Log.d("listItemHeight" + listItem.getMeasuredHeight(), "___________");
            }
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = (int) ((totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))));
            listView.setLayoutParams(params);
            listView.requestLayout();

        }
    });
   }

答案 3 :(得分:1)

不建议在ScrollView中使用ListView

答案 4 :(得分:1)

您可以使用以下方法以编程方式设置listview的高度:

<ListView
        android:id="@+id/lvMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        />

用于设置listview高度的方法:

public static boolean setListViewHeightBasedOnItems(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter != null) {

            int numberOfItems = listAdapter.getCount();

            // Get total height of all items.
            int totalItemsHeight = 0;
            for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
                View item = listAdapter.getView(itemPos, null, listView);
                float px = 500 * (listView.getResources().getDisplayMetrics().density);
                item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                totalItemsHeight += item.getMeasuredHeight();
            }

            // Get total height of all item dividers.
            int totalDividersHeight = listView.getDividerHeight() *
                    (numberOfItems - 1);
            // Get padding
            int totalPadding = listView.getPaddingTop() + listView.getPaddingBottom();

            // Set list height.
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalItemsHeight + totalDividersHeight + totalPadding;
            listView.setLayoutParams(params);
            listView.requestLayout();
            return true;

        } else {
            return false;
        }

    }

然后设置如下代码:

 MenuAdapter menuAdapter = new MenuAdapter(context, R.layout.menu_item);
            lvMenu.setAdapter(menuAdapter);
            setListViewHeightBasedOnItems(lvMenu);

答案 5 :(得分:0)

  

此类可用于在运行时扩展listview或gridview的高度,请将其放入包中并通过listview使用

public class CustomView {

        public static void getListViewSize(ListView myListView) {
            ListAdapter myListAdapter = myListView.getAdapter();
            if (myListAdapter == null) {
                //do nothing return null
                return;
            }
            //set listAdapter in loop for getting final size
            int totalHeight = 0;
            for (int size = 0; size < myListAdapter.getCount(); size++) {
                View listItem = myListAdapter.getView(size, null, myListView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
            //setting listview item in adapter
            ViewGroup.LayoutParams params = myListView.getLayoutParams();
            params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
            myListView.setLayoutParams(params);
            // print height of adapter on log
            Log.i("height of listItem:", String.valueOf(totalHeight));
        }



        public static void getGridViewSize(GridView myGridView) {
            ListAdapter myListAdapter = myGridView.getAdapter();
            if (myListAdapter == null) {
                //do nothing return null
                return;
            }
            //set listAdapter in loop for getting final size
            int totalHeight = 0;
            int maxHeight = 0;//implement new 
            for (int size = 0; size < myListAdapter.getCount(); size++) {
                View listItem = myListAdapter.getView(size, null, myGridView);

                listItem.measure(0, 0);

                totalHeight += listItem.getMeasuredHeight()+8;

                if(maxHeight < listItem.getMeasuredHeight()){//implement new 

                    maxHeight = listItem.getMeasuredHeight()+8;
                    System.out.println(" max height of gridview item<11>  "+size+"  ==  "+maxHeight);
                }

                System.out.println(myListAdapter.getCount()+"  height of gridview item<22>  "+size+"  ==  "+listItem.getMeasuredHeight());
            }

            //setting listview item in adapter
             ViewGroup.LayoutParams params = myGridView.getLayoutParams();

            if(myListAdapter.getCount() > 1)
                params.height = maxHeight * ((myListAdapter.getCount()+1)/2);//implement new
            else
                params.height = maxHeight;//implement new

             myGridView.setLayoutParams(params);

        }


    }

答案 6 :(得分:0)

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

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

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

答案 7 :(得分:0)

&#13;
&#13;
 <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <ListView
                android:id="@+id/lv_premimum_upgrade"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/custom_margin"
                android:minHeight="48dp">
            </ListView>
        </LinearLayout> 

</ScrollView>
&#13;
&#13;
&#13;

&#13;
&#13;
int list_cell_size=188;    // cell_size is varible 
ViewGroup.LayoutParams list;
list = (ViewGroup.LayoutParams) listView.getLayoutParams();
list.height = list_cell_size*response.size();  // response is list items size
listView.setLayoutParams(list);
&#13;
&#13;
&#13;