Android custom ListView centered development
By customizing a list ListView is centered overall
Custom ListView:
as follows
public class HorizentalCenterListView extends ListView {
public HorizentalCenterListView(Context context) {
super(context);
}
public HorizentalCenterListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public HorizentalCenterListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getMaxWidthOfChildren() + getPaddingLeft() + getPaddingRight();//计算listview的宽度
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightMeasureSpec);//设置listview的宽高
}
/**
* 计算item的最大宽度
*
* @return
*/
private int getMaxWidthOfChildren() {
int maxWidth = 0;
View view = null;
if (getAdapter() != null) {
int count = getAdapter().getCount();
for (int i = 0; i < count; i++) {
view = getAdapter().getView(i, view, this);
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
if (view.getMeasuredWidth() > maxWidth)
maxWidth = view.getMeasuredWidth();
}
}
return maxWidth;
}
}
Layout file:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.zzs.view.HorizentalCenterListView
android:id="@+id/hclv_main_item"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:divider="@null"
android:dividerHeight="0dp"
android:scrollbars="none" />
</RelativeLayout>
Other uses of the same and ListView