如何创建一个按钮,该按钮在按下时进入日历视图,允许用户选择日期?



如何对按下时进入日历视图的按钮进行编码,从而允许用户选择日期?(在主活动和 xml 中(

当您可以自己完成时,无需添加库.....我在这里使用了editText,你可以做任何事情,一个图像,一个按钮,文本视图

主活动

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
editText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate=Calendar.getInstance();
int year = mcurrentDate.get(Calendar.YEAR);
int month = mcurrentDate.get(Calendar.MONTH);
int day = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) {
// TODO Auto-generated method stub
/*      Your code   to get date and time    */
Log.e("Date Selected", "Month: " + selectedMonth + " Day: " + selectedDay + " Year: " + selectedYear);
editText.setText(selectedMonth + "/" + selectedDay + "/" + selectedYear);
}
},year, month, day);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
}
}

.XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.vzw.www.myapplication.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"/>
</android.support.constraint.ConstraintLayout>

相关内容

  • 没有找到相关文章

最新更新