1.概要:
为什么不直接为EditTText设置一个点击监听器,而非要使用Button呢?
答案是:使用Button更安全,因为用户无法修改Button的文本内容。如果使用EditText,并且只设置了点击监听器,用户可以通过光标获取该
控件的焦点,这样便可以绕过DatePicker控件直接修改EditText的文本内容
2.实现思路:
将Button的背景设置成EditText的背景,在点击后弹去DatePicker控件,选定好时间后修改BUutton的text
3.效果图:
4.代码:
1 public class MainActivity extends Activity { 2 3 private Button btn; 4 private int year; 5 private int month; 6 private int day; 7 private DatePickerDialog datePickDialog; 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_main); 13 btn = (Button) findViewById(R.id.btn); 14 Calendar calendar = Calendar.getInstance(); 15 year = calendar.get(Calendar.YEAR); 16 month = calendar.get(Calendar.MONTH); 17 day = calendar.get(Calendar.DAY_OF_MONTH); 18 datePickDialog = new DatePickerDialog(MainActivity.this, 19 new OnDateSetListener() { 20 21 @Override 22 public void onDateSet(DatePicker view, int year, 23 int monthOfYear, int dayOfMonth) { 24 btn.setText(year + "/" + monthOfYear + "/" + dayOfMonth); 25 } 26 }, year, month, day); 27 28 btn.setOnClickListener(new OnClickListener() { 29 30 @Override 31 public void onClick(View v) { 32 datePickDialog.show(); 33 } 34 }); 35 } 36 37 }
activity_main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 tools:context=".MainActivity" > 7 8 <Button 9 android:id="@+id/btn" 10 android:layout_width="match_parent" 11 android:layout_height="wrap_content" 12 android:background="@android:drawable/edit_text" /> 13 14 </LinearLayout>
时间: 2024-10-13 11:25:28