改变DatePicker和TimePicker大小,使之横向并列展示

    今天项目中使用到了日期+时分选择控件,由于系统有DatePicker和TimePicker所以不想再去写控件或者找开源项目,但是这两个控件横向排列却又太大了,于是去网上查了一些方法来修改控件大小,可是这些方法都是通过修改子控件大小和字体大小来实现改变两个控件大小的,这种方法感觉在5.0上可能不会适用(在Android Studio上预览这两个控件变化比较大),而且实现方式过于复杂,于是考虑使用简便且通用一些的方式来实现,总归功夫不负有心人,顺利完成.

1.修改FrameLayout的onmeasure方法.

public class MyWrapContentView extends FrameLayout {
    public MyWrapContentView(Context context) {
        super(context);
    }

    public MyWrapContentView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyWrapContentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.AT_MOST,0);//核心代码
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

2.使用该控件包裹DatePicker和TimePicker

    <cn.schope.lrr.view.MyWrapContentView
        android:layout_gravity="center" #此处必需设置居中,外层是Relativelayout就用centerinparent,是LinearLayout便用layoutgravity
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <LinearLayout
        android:layout_gravity="center"
        android:id="@+id/ll_picker"
        android:layout_width="wrap_content"#使用包裹体
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <DatePicker
            android:id="@+id/dp_submit_day"
            android:layout_width="wrap_content"#使用包裹体
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />
        <TimePicker
            android:layout_width="wrap_content"#使用包裹体
            android:layout_height="wrap_content"
            android:id="@+id/time_picker"/>
    </LinearLayout>
    </cn.schope.lrr.view.MyWrapContentView>

3.使用Nineoldandroids开源库中的ViewHelper缩放控件.(V4包的ViewCompat也可)

        View ll_picker = view.findViewById(R.id.ll_picker);
        ViewHelper.setScaleX(ll_picker,0.8f);//可以随意指定缩小百分比
        ViewHelper.setScaleY(ll_picker,0.8f);

如此就可以实现DatePicker和TimePicker横向并列显示了.

发布了24 篇原创文章 · 获赞 5 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/g707175425/article/details/47044811