Yes, you can have your custom ListView
with a maxHeight
property.
Step 1. Create attrs.xml
file inside the values
folder and put the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ListViewMaxHeight">
<attr name="maxHeight" format="dimension" />
</declare-styleable>
</resources>
Step 2. Create a new class (ListViewMaxHeight.java
) and extend the ListView
class:
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);
}
}
Step 3. In the xml file of your layout:
<com.example.myapp.ListViewMaxHeight
android:layout_width="match_parent"
android:layout_height="match_parent"
app:maxHeight="120dp" />