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

lan*_*nyf 4 height android android-listview

有一个listView,如果它的内容较少,它的高度应该随之而来"wrap_content".如果它有更多行,则最大高度应限制在某个高度.

它允许设置android:maxHeightListView:

<ListView>
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="120dp"
</ListView>
Run Code Online (Sandbox Code Playgroud)

但它总是不起作用"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);
Run Code Online (Sandbox Code Playgroud)

有没有办法在xml中做到这一点?

小智 8

是的,您可以ListView使用maxHeight房产进行定制.

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

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

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

</resources>
Run Code Online (Sandbox Code Playgroud)

步骤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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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

<com.example.myapp.ListViewMaxHeight
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:maxHeight="120dp" />
Run Code Online (Sandbox Code Playgroud)