标签:
最近几天再做一个App开发,开发时需要使用DatePickerDialog来只显示年月,在网上参考了不少的例子,有的自己琢磨不透,所幸看到了(这里请参考http://whb198900.blog.163.com/blog/static/766453542012108111920879)这位朋友的文章以及http://download.csdn.net/detail/u010372772/6027761这里边的代码,自己又进行了总结,总之,完成了自己的任务。
1 public class SecondActivity extends Activity implements OnClickListener {
2 /** Called when the activity is first created. */
3 private Button button;
4 private EditText textview;
5 private Dialog mdialog;
6 private Calendar calendar = null;
7
8 @Override
9 public void onCreate(Bundle savedInstanceState) {
10 super.onCreate(savedInstanceState);
11 requestWindowFeature(Window.FEATURE_NO_TITLE);
12 setContentView(R.layout.second);
13
14 initUi();
15 button.setOnClickListener(this);
16 }
17
18 public void initUi() {
19 button = (Button) findViewById(R.id.show);
20 textview = (EditText) findViewById(R.id.editText);
21 }
22
23 @Override
24 public void onClick(View v) {
25 // TODO Auto-generated method stub
26 showDialog(0);// 日期弹出框
27 int SDKVersion = SecondActivity.this.getSDKVersionNumber();// 获取系统版本
28 System.out.println("SDKVersion = " + SDKVersion);
29 DatePicker dp = findDatePicker((ViewGroup) mdialog.getWindow()
30 .getDecorView());// 设置弹出年月日
31 if (dp != null) {
32 if (SDKVersion < 11) {
33 ((ViewGroup) dp.getChildAt(0)).getChildAt(1).setVisibility(
34 View.GONE);
35 } else if (SDKVersion > 14) {
36 //只显示年月
37 ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0))
38 .getChildAt(1).setVisibility(View.GONE);//.getChildAt(0)
39 //只显示年日
40 // ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0))
41 // .getChildAt(2).setVisibility(View.GONE);
42 //只显示年月
43 // ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0))
44 // .getChildAt(1).setVisibility(View.GONE);
45 //显示月日
46 // ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0))
47 // .getChildAt(0).setVisibility(View.GONE);
48 }
49 }
50
51 }
52
53 @Override
54 protected Dialog onCreateDialog(int id) { // 对应上面的showDialog(0);//日期弹出框
55 mdialog = null;
56 switch (id) {
57 case 0:
58 calendar = Calendar.getInstance();
59 mdialog = new DatePickerDialog(this,
60 new DatePickerDialog.OnDateSetListener() {
61 @Override
62 public void onDateSet(DatePicker view, int year,
63 int monthOfYear, int dayOfMonth) {
64 textview.setText(year + "-" + (monthOfYear));
65 }
66 }, calendar.get(Calendar.YEAR),
67 calendar.get(Calendar.MONTH),
68 calendar.get(Calendar.DAY_OF_MONTH));
69 break;
70 }
71 return mdialog;
72 }
73
74 /**
75 * 从当前Dialog中查找DatePicker子控件
76 *
77 * @param group
78 * @return
79 */
80 private DatePicker findDatePicker(ViewGroup group) {
81 if (group != null) {
82 for (int i = 0, j = group.getChildCount(); i < j; i++) {
83 View child = group.getChildAt(i);
84 if (child instanceof DatePicker) {
85 return (DatePicker) child;
86 } else if (child instanceof ViewGroup) {
87 DatePicker result = findDatePicker((ViewGroup) child);
88 if (result != null)
89 return result;
90