是否可以在xml中设置listView maxHeight?

时间:2015-05-04 17:43:59

标签: android android-listview height

拥有listView,如果内容较少,则其高度应与"wrap_content"一致。如果它有更多行,则最大高度应限制在某个高度。

允许在android:maxHeight中设置ListView

<ListView>
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="120dp"
</ListView>

但它不起作用且总是"wrap_content"。 只有使其工作的方法是代码使用

int cHeight = parentContainer.getHeight();
ViewGroup.LayoutParams lp = mListView.getLayoutParams();

if (messageListRow > n) 
{
    lp.height = (int)(cHeight * 0.333);
} 
else 
{
    lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
}

mListView.setLayoutParams(lp);

有没有办法在xml中完成?

1 个答案:

答案 0 :(得分:8)

是的,您可以将自定义ListView设为maxHeight属性。

步骤1.在attrs.xml文件夹中创建values文件并输入以下代码:

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

    <declare-styleable name="ListViewMaxHeight">
        <attr name="maxHeight" format="dimension" />
    </declare-styleable>

</resources>

步骤2.创建一个新类(ListViewMaxHeight.java)并扩展ListView类:

package com.example.myapp;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ListView;

public class ListViewMaxHeight extends ListView {

    private final int maxHeight;

    public ListViewMaxHeight(Context context) {
        this(context, null);
    }

    public ListViewMaxHeight(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ListViewMaxHeight(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ListViewMaxHeight);
            maxHeight = a.getDimensionPixelSize(R.styleable.ListViewMaxHeight_maxHeight, Integer.MAX_VALUE);
            a.recycle();
        } else {
            maxHeight = 0;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (maxHeight > 0 && maxHeight < measuredHeight) {
            int measureMode = MeasureSpec.getMode(heightMeasureSpec);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, measureMode);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}

步骤3.在布局的xml文件中:

<com.example.myapp.ListViewMaxHeight
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:maxHeight="120dp" />