浏览 3906 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-07-23
java.lang.Object ↳android.view.View ↳android.view.ViewGroup ↳android.widget.FrameLayout ↳android.widget.DatePicker android.widget.DatePicker继承了android.widget.FrameLayout框架布局类。DatePicker例子如图7-7所示,从左到右是年、月、日的设置,改变年月日都会触发OnDateChanged事件,当点击“按钮”可以获得当前设置的时间。 ![]() 图7-7 DatePicker 请参考代码清单7-6,完整代码请参考chapter7_1工程中chapter7_DatePicker代码部分。 【代码清单7-6】 public class chapter7_DatePicker extends Activity { private TextView mDateDisplay; private DatePicker datePicker; private Calendar c; private Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.datepicker_layout); datePicker = (DatePicker) findViewById(R.id.datePicker); c = Calendar.getInstance(); mDateDisplay = (TextView) findViewById(R.id.datetextview); datePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c .get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() { public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mDateDisplay.setText("[" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + "]" + "[" + view.getYear() + "-" + (view.getMonth() + 1) + "-" + view.getDayOfMonth() + "]"); } }); button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mDateDisplay.setText(String.valueOf(datePicker.getYear()) + " - " + String.valueOf(datePicker.getMonth() + 1) + " - " + String.valueOf(datePicker.getDayOfMonth())); } }); } } Calendar.getInstance()会获得一个Calendar实例,这是一个日期实例,通过它的get(Calendar.YEAR)方法可以获得年,get(Calendar.MONTH)方法加1获得月, get(Calendar.DAY_OF_MONTH)方法获得日期。DataPicker控件的核心代码是init方法: datePicker.init(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {…} 在init方法中初始化DataPicker和事件的处理。 DataPicker的布局文件请参考代码清单7-7,完整代码请参考chapter7_1工程中datepicker_layout.xml代码部分(chapter7_1/res/layout/datepicker_layout.xml)。 【代码清单7-7】 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content"> </DatePicker> <TextView android:id="@+id/datetextview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:text="按钮" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |