在工作中发现Android原生的datePicker和timePicker存在一些问题,并不好用,所以自己编写了自定义的datePickerActivity来满足需求。希望能给其他需要的人提供借鉴,让自己以后遇到类似问题可以很方便的直接使用。其效果如图:
细节讲解
- 移动焦点时对组件背景的改变
yearPicker.setOnFocusChangeListener(new View.OnFocusChangeListener(){
@Override
public void onFocusChange(View view, boolean b) {
if (getCurrentFocus() == view){
Log.i(TAG,"---yearPicker---");
yearPicker.setBackground(getResources().getDrawable(R.drawable.button1));
}
else{
Log.i(TAG,"---loseYearPicker---");
yearPicker.setBackgroundColor(Color.alpha(R.color.colorNone));
}
}
});
代码
yearPicker.setBackground(getResources().getDrawable(R.drawable.button1));
在不适合API 16以下的版本,所以可以用
yearPicker.setBackgroundDrawable(getResources().getDrawable(R.drawable.button1));
代替。
使用方法
- 点击“确定”按钮返回日期和时间(String类型)。通过intent传递bundle。
- 点击“取消”按钮不返回数据。
- 在styles.xml中添加MyDialogStyle。
- 在drawable中添加图片。
- 在AndroidManifest.xml中添加代码:
<activity android:name=".DatePickerActivity"
android:theme="@style/MyDialogStyle" /> - 使用如下方法来启动datePickerActivity:
startActivityForResult(new Intent(XXXActivity.this,DatePickerActivity.class),0);