Android开发自定义ListView居中显示

Android开发自定义ListView居中显示

通过自定义ListView是列表整体居中显示

自定义ListView:

如下

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;
    }

}

布局文件:

<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>

其它用法和ListView一样

发布了22 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36158551/article/details/82529685