一、 实现效果
外观仿横线编辑框的按钮,点击按钮,横线颜色改变,随后弹出日期选择对话框。修改对话框中的值,按钮文字内容相应改变。
1、按钮点击前
2、按钮点击时
3、按钮点击后
二、XML布局
1、Button所在布局文件
<Button
android:id="@+id/button_start_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:layout_marginEnd="3dp"
android:gravity="center"
style="?android:attr/buttonBarButtonStyle"
android:background="@drawable/background_edittext_inside_click"
android:textSize="14sp"
android:textColor="@color/color_text_primary"
android:onClick="startDateOnClick" />
2、background_edittext_inside_click.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:state_pressed="false"
android:drawable="@drawable/shape_edittext_inside_false" />
<item
android:state_pressed="true"
android:drawable="@drawable/shape_edittext_inside_true" />
</selector>
3、shape_edittext_inside_false.xml (默认状态)
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 横线颜色 -->
<item>
<shape>
<solid android:color="@color/#" />
</shape>
</item>
<!-- 背景颜色,注意要和Button所在组件Background保持一致 -->
<item
android:bottom="1dp" >
<shape>
<solid android:color="@color/#" />
</shape>
</item>
</layer-list>
4、shape_edittext_inside_true.xml (点击状态)
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 横线颜色 -->
<item>
<shape>
<solid android:color="@color/color_edittext_main_true" />
</shape>
</item>
<item
android:bottom="1dp" >
<!-- 背景颜色 -->
<shape>
<solid android:color="@color/color_edittext_inside_background" />
</shape>
</item>
</layer-list>
三、设置监听
1、定义相关变量
private Button button_start_date;
private DatePickerDialog dialog_datepicker;
private int year1,month1,day1;
2、初始化显示
Calendar calendar;
calendar = Calendar.getInstance();
year1 = calendar.get(Calendar.YEAR);//获取年份
month1 = calendar.get(Calendar.MONTH)+1;//获取月份
day1 = calendar.get(Calendar.DATE);//获取日
minute1 = calendar.get(Calendar.MINUTE);//分
hour1 = calendar.get(Calendar.HOUR_OF_DAY);//小时
button_start_date = (Button)findViewById(R.id.button_start_date);
// 默认时间显示
button_start_date.setText("" + year1 + " 年 " + month1 + " 月 " + day1 + " 日");
3、Button的监听事件
public void startDateOnClick(View Source) {
// 标记位,用于分辨为开始还是结束时间
flag = 1;
// 弹出选择对话框
dialog_datepicker.show();
}
4、DataPickerDialog 定义
dialog_datepicker = new DatePickerDialog(this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year1 = year;
month1 = monthOfYear+1;
day1 = dayOfMonth;
button_start_date.setText("" + year1 + " 年 " + month1 + " 月 " + day1 + " 日");
}
}, year1, month1-1, day1);