activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pick a date" android:onClick="showDatePickerDialog" android:id="@+id/button" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:id="@+id/selected_date" android:layout_below="@+id/button" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="54dp" /> </RelativeLayout>
MainActivity.java
package in.blogspot.kantapp.androiddatepickerexample; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.DatePicker; import android.widget.TextView; import java.util.Calendar; public class MainActivity extends ActionBarActivity { public static TextView SelectedDateView; public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { SelectedDateView.setText("Selected Date: " + (month + 1) + "-" + day + "-" + year); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SelectedDateView = (TextView) findViewById(R.id.selected_date); } public void showDatePickerDialog(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } }
No comments:
Post a Comment