是的,你可以有你的自定義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" />
請勿將「wrap_content」用於listview的高度,因爲這會導致您的適配器被多次調用。爲什麼不把你的listview放在LinearLayout容器中,而是根據你的需求來控制高度。 – Pztar
好點,謝謝Pztar。但即使放入LinearLayout容器,定義容器的高度仍然是個問題。也許動態設置代碼是唯一的方法。 – lannyf