trying to solve my timer error in android stuido.
i have 2 xml text views where one is start time and one is finsih time
a user must choose there start and finish time to fill in the details
i have most the code correct just cant figure out this one line
also would like if possible i know its already working but for my date picker how do i make say "Friday 3/04/2020"
here is my main java class
public class ChoseSession extends AppCompatActivity implements AdapterView.OnItemSelectedListener
{
private static final String TAG = "ChooseSession";
private TextView displayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private TextView displayStartTime;
private TextView displayFinishTime;
private TimePickerDialog.OnTimeSetListener mSTimeSetListener;
private TimePickerDialog.OnTimeSetListener mFTimeSetListener;
//------------------------------------------------------------------------------------------------
public Button confirmbookingBTN;
public void returnMain()
{
confirmbookingBTN = (Button)findViewById(R.id.confirmBooking);
confirmbookingBTN.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent book = new Intent(ChoseSession.this, Results.class);
startActivity(book);
}
});
}
//-----------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chose_session);
//-----------------------------------------------------------------------------------------------
returnMain();
//-----------------------------------------------------------------------------------------------
displayStartTime = findViewById(R.id.startTimeView);
displayFinishTime = findViewById(R.id.finishTimeView);
displayStartTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
TimePickerDialog timedialog = new TimePickerDialog(this, hour, minute, DateFormat.is24HourFormat(getContext())););
timedialog.getWindow().setBackgroundDrawable((new ColorDrawable((Color.TRANSPARENT))));
timedialog.show();
}
});
displayFinishTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
TimePickerDialog timedialog = new TimePickerDialog(this, hour, minute, DateFormat.is24HourFormat(getContext())););
timedialog.getWindow().setBackgroundDrawable((new ColorDrawable((Color.TRANSPARENT))));
timedialog.show();
}
});
mSTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayStartTime.setText((hourOfDay+":"+minute));
}
};
mFTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayFinishTime.setText((hourOfDay+":"+minute));
}
};
//-----------------------------------------------------------------------------------------------
displayDate = (TextView) findViewById(R.id.dateView);
displayDate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(ChoseSession.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener, year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int y, int m, int d)
{
m = m + 1;
Log.d(TAG, "onDataSet: date: " + y + "/" + m + "/" + d);
String date = d+"/"+m+"/"+"/"+y;
displayDate.setText(date);
}
};
//-----------------------------------------------------------------------------------------------
Spinner sSpinner = findViewById(R.id.spinnerSessionChoosing);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sessionNames, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sSpinner.setAdapter(adapter);
sSpinner.setOnItemSelectedListener(this);
//-----------------------------------------------------------------------------------------------
}
private Context getContext()
{
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String textSession = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), textSession, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
//-----------------------------------------------------------------------------------------------
}
my XML
<TextView
android:id="#+id/finishTimeView"
android:layout_width="161dp"
android:layout_height="25dp"
android:layout_marginEnd="44dp"
android:layout_marginBottom="99dp"
android:text="Choose Finish Time"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/confirmBooking"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/timefinishText"
app:layout_constraintTop_toBottomOf="#+id/startTimeView" />
<TextView
android:id="#+id/startTimeView"
android:layout_width="161dp"
android:layout_height="25dp"
android:layout_marginEnd="44dp"
android:layout_marginBottom="40dp"
android:text="Choose Start Time"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/finishTimeView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/timestartText"
app:layout_constraintTop_toBottomOf="#+id/dateView" />
the answer to the java time dialog
displayStartTime = findViewById(R.id.startTimeView);
displayFinishTime = findViewById(R.id.finishTimeView);
displayStartTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final int min = cal.get(Calendar.MINUTE);
TimePickerDialog sTimePickerDialog = new TimePickerDialog(tContext, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayStartTime.setText(hourOfDay+":"+minute);
}
},hour, min, android.text.format.DateFormat.is24HourFormat(tContext));
sTimePickerDialog.show();
}
});
displayFinishTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final int min = cal.get(Calendar.MINUTE);
TimePickerDialog fTimePickerDialog = new TimePickerDialog(tContext, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayFinishTime.setText(hourOfDay+":"+minute);
}
},hour, min, android.text.format.DateFormat.is24HourFormat(tContext));
fTimePickerDialog.show();
}
});
Related
I'm creating an app with two DatePicker to set a start and an end dates. As the DatePicker are called from DialogFragments, I set two tags to differentiate the results in the main activity:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sel_start_date:
DialogFragment startDatePicker = new DatePickerFragment();
startDatePicker.show(getSupportFragmentManager(), START_DATE_PICKER_TAG);
break;
case R.id.sel_end_date:
DialogFragment endDatePicker = new DatePickerFragment();
endDatePicker.show(getSupportFragmentManager(), END_DATE_PICKER_TAG);
break;
The DatePickerFragment class:
public class DatePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day );
}
and this is how I get the result in the main activity
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
if (view.getTag().equals(START_DATE_PICKER_TAG)) {
calendarStartDate.set(Calendar.YEAR, year);
calendarStartDate.set(Calendar.MONTH, month);
calendarStartDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
start_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
} else {
calendarEndDate.set(Calendar.YEAR, year);
calendarEndDate.set(Calendar.MONTH, month);
calendarEndDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
end_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}
However, I get a nullPointerException doing view.getTag(). How can I solve this, or how else can I diferentiate the results?
Aclaration: DatePickerDialog is a native class, not one which I created, so I can't edit their methods`
TimePickerFragment:
public class TimePickerFragment extends DialogFragment {
private static final String ARGS_TAG = "ARGS_TAG";
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
final String tag = getArguments().getString(ARGS_TAG);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, android.text.format.DateFormat.is24HourFormat(getActivity())) {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
};
}
public static TimePickerFragment newInstance(String tag){
Bundle args = new Bundle();
args.putString(ARGS_TAG, tag);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
Solution: Define two interface to forward data from fragments to activity.
Step 1. Define OnDateSetListener interface to communicate between MainActivity and DatePickerFragment.
public interface OnDateSetListener {
void onDateSet(String tag, DatePicker view, int year, int month, int dayOfMonth);
}
Step 2. Define OnTimeSetListener interface to communicate between MainActivity and TimePickerFragment.
public interface OnTimeSetListener {
void onTimeSet(String tag, TimePicker view, int hourOfDay, int minute);
}
Step 3. Let MainActivity implements both of interfaces.
public class MainActivity extends AppCompatActivity implements OnDateSetListener, OnTimeSetListener {
// Your code her
...
#Override
public void onDateSet(String tag, DatePicker view, int year, int month, int dayOfMonth) {
// Process code with tag here
}
#Override
public void onTimeSet(String tag, TimePicker view, int hourOfDay, int minute) {
// Process code with tag here.
}
}
Step 4. Change code in DatePickerFragment
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
private static final String ARGUMENT_TAG = "ARGUMENT_TAG";
public static DatePickerFragment newInstance(String tag) {
Bundle args = new Bundle();
args.putString(ARGUMENT_TAG, tag);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(requireActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
final String tag = getArguments().getString(ARGUMENT_TAG);
OnDateSetListener listener = (OnDateSetListener) requireActivity();
listener.onDateSet(tag, view, year, month, dayOfMonth);
}
}
Step 5. Change code in TimePickerFragment.
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static final String ARGS_TAG = "ARGS_TAG";
public static TimePickerFragment newInstance(String tag) {
Bundle args = new Bundle();
args.putString(ARGS_TAG, tag);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return new TimePickerDialog(requireActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
final String tag = getArguments().getString(ARGS_TAG);
OnTimeSetListener listener = (OnTimeSetListener) requireActivity();
listener.onTimeSet(tag, view, hourOfDay, minute);
}
}
As I see, you've set the tag to the Fragment, but what you're trying to get is the tag of the View. They are not the same thing, as a view's tag is an object, while a fragment's tag is a string.
As you can see your view in onDateSet is a DatePicker, and you set your tag on the fragment containing the DatePicker, which is the DatePickerDialog.
So to get your tag you should try something like:
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
if (view.getParent() != null && view.getParent().getTag().equals(START_DATE_PICKER_TAG)) {
calendarStartDate.set(Calendar.YEAR, year);
calendarStartDate.set(Calendar.MONTH, month);
calendarStartDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
start_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
} else {
calendarEndDate.set(Calendar.YEAR, year);
calendarEndDate.set(Calendar.MONTH, month);
calendarEndDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
end_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}
I am kind of stuck on my project. I am asking for help on the datepicker format I managed to display my one on a TextView in full format.
However, after doing some coding in java, when I call in a date picker and pick a new date, it updates in short format, for example.
Current date Friday, January, 20 2017 after using date picker it shows 20-1-17
I want it to display in full, please help, below is my Java code
public class EntryEdit extends AppCompatActivity {
TextView textView;
int year_x, month_x, day_x;
static final int DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_edit);
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
showDialogOnTextViewClick();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(new Date());
TextView textView = (TextView) findViewById(R.id.date);
textView.setText(currentDateString);
}
public void showDialogOnTextViewClick() {
textView = (TextView) findViewById(R.id.date);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new DatePickerDialog(this, dpickerListener, year_x, month_x, day_x);
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x = year;
month_x = month +1;
day_x = dayOfMonth;
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(new Date());
updateStartDisplay();
}
};
private void updateStartDisplay() {
textView.setText(new StringBuilder()
// Month is 0 based so add 1
.append(day_x + 1).append("-").append(month_x).append("-")
.append(year_x).append(" "));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu2, menu);
return true;
}
The reason why your textView shows 20-1-2017 is because each time you pick a date in a DatePicker, you call updateStartDisplay() method, where you specifically set the text to be day-month-year.
Here's one possible solution:
private DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x = year;
month_x = month;
day_x = dayOfMonth;
Calendar calendar = Calendar.getInstance();
calendar.set(year_x, month_x, day_x);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
textView.setText(currentDateString);
}
};
I have the following as AppCompatSpinner's entries:
<string-array name="startTimeList">
<item>Now</item>
<item>Pick a time..</item>
</string-array>
Upon selecting Pick a time.., a TimePickerDialog is opened and the user is allowed to choose a time. Here's how:
startTimeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// startTimeString = adapterView.getItemAtPosition(i).toString();
DateFormat currentDateFormat = new SimpleDateFormat("HH:mm:ss");
userAvailableTimeInSF = currentDateFormat.format(new Date());
final TextView startTimeSpinnerTV = (TextView) adapterView.getSelectedView();
startTimeSpinnerTV.setText(userAvailableTimeInSF);
switch (i) {
case 0:
userAvailableTimeInSF = currentDateFormat.format(new Date());
startTimeSpinnerTV.setText("Now");
break;
default:
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(PostSportRequest.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
Calendar date = Calendar.getInstance();
date.set(Calendar.HOUR_OF_DAY, hourOfDay);
date.set(Calendar.MINUTE, minute);
date.set(Calendar.AM_PM, date.get(Calendar.AM_PM));
showTime(hourOfDay, minute);
userAvailableTimeInSF = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
startTimeSpinnerTV.setText(userAvailableTimeAMPM);
Toast.makeText(getBaseContext(), "userAvailableTimeInSF: " + userAvailableTimeInSF, Toast.LENGTH_SHORT).show();
}
}, mHour, mMinute, false);
timePickerDialog.show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Upon selecting Pick a time.. the first time, TimePickerDialog is successfully opened and the chosen time is shown but when I choose it again or click on it again, nothing happens!
I don't know why!
Please let me know how can I get the TimePickerDialog opened and chose the time no matter how many times I select/click it.
Follow these steps:
Create a custom spinner class
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
public class SpinnerOnSameSelection extends Spinner {
OnItemSelectedListener listener;
private AdapterView<?> lastParent;
private View lastView;
private long lastId;
public SpinnerOnSameSelection(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initlistner();
}
#Override
public void setSelection(int position) {
if (position == getSelectedItemPosition() && listener != null) {
listener.onItemSelected(lastParent, lastView, position, lastId);
} else {
super.setSelection(position);
}
}
private void initlistner() {
// TODO Auto-generated method stub
super.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
lastParent = parent;
lastView = view;
lastId = id;
if (listener != null) {
listener.onItemSelected(parent, view, position, id);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onNothingSelected(parent);
}
}
});
}
public void setOnItemSelectedEvenIfUnchangedListener(
OnItemSelectedListener listener) {
this.listener = listener;
}
}
Create onItemSelectedListener in your activity
private AdapterView.OnItemSelectedListener listener;
listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View arg1,
int i, long arg3) {
//startTimeString = adapterView.getItemAtPosition(i).toString();
DateFormat currentDateFormat = new SimpleDateFormat("HH:mm:ss");
userAvailableTimeInSF = currentDateFormat.format(new Date());
final TextView startTimeSpinnerTV = (TextView) adapterView.getSelectedView();
startTimeSpinnerTV.setText(userAvailableTimeInSF);
switch (i) {
case 0:
// userAvailableTimeInSF = currentDateFormat.format(new Date());
startTimeSpinnerTV.setText("Now");
break;
case 1:
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
Calendar date = Calendar.getInstance();
date.set(Calendar.HOUR_OF_DAY, hourOfDay);
date.set(Calendar.MINUTE, minute);
date.set(Calendar.AM_PM, date.get(Calendar.AM_PM));
//showTime(hourOfDay, minute);
/* userAvailableTimeInSF = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
startTimeSpinnerTV.setText(userAvailableTimeAMPM);*/
Toast.makeText(getBaseContext(), "userAvailableTimeInSF: " + userAvailableTimeInSF, Toast.LENGTH_SHORT).show();
}
}, mHour, mMinute, false);
timePickerDialog.show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
}
Add the listener object to custom spinner method
SpinnerOnSameSelection startTimeSpinner;
in onCreate(): startTimeSpinner = (SpinnerOnSameSelection) findViewById(R.id.idOfItemInXml);
startTimeSpinner.setOnItemSelectedEvenIfUnchangedListener(listener);
In Your xml File
<your_package_name.SpinnerOnSameSelection
android:id="#+id/startTimeSpinner"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:entries="#array/mList">
</your_package_name.SpinnerOnSameSelection>
Spinner (or actually AdapterView, its superclass), fires OnItemSelectedListener only when the selection changes.
When your user selects "Pick a time..." Spinner assumes it is a selected option, and won't call the listener anymore if it is selected again. You can however notice, that if "Pick a time..." is selected, then "Now" and then "Pick a time...", the dialog appears.
I would recommend against using Spinner in your case (and doing some weird shit with the selected view). You can simply accomplish the same with TextView that displays the selected time and two buttons - one to show the dialog and one to reset the time to now.
I am trying to make the date picker appear in a dialog fragment upon clicking the date field to write/set the date I selected with the use of the DatePicker. Unfortunately, each time I click, the DatePicker doesn't show up.
Below is the the code of the class:
public class UpdateGrade extends DialogFragment{
private EditText dateField;
static final int DATE_DIALOG_ID = 0;
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(getActivity(), mDateSetListener, cyear, cmonth, cday);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String date_selected =String.valueOf(monthOfYear+1)+"-"+String.valueOf(dayOfMonth)+"-"+String.valueOf(year);
dateField.setText(date_selected);
}
};
#SuppressLint("SimpleDateFormat")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.update_grade_layout, container);
getDialog().getWindow().requestFeature(STYLE_NO_TITLE);
dateField = (EditText) view.findViewById(R.id.dateField);
dateField.setOnTouchListener(new OnTouchListener(){
#SuppressWarnings("deprecation")
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(v == dateField)
getActivity().showDialog(DATE_DIALOG_ID);
return false;
}
});
return view;
}
Thank you!
You have to define the onCreateDialog() method to return an instance of DatePickerDialog:
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) {
// Do something with the date chosen by the user
}
}
More information here.
is it possible to make a date picker in android app as in an iPhone app.
i saw a date picker in i phone app having a Done and cancel buttons. the month , year and date are been chosen by scrolling it, how can i make such a one in my android app
DatePicker and Date Picker tutorial.
Your XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/dateDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<Button android:id="#+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date Picker"/>
</LinearLayout>
Your Activity Class
public class pickerdate extends Activity {
/** Called when the activity is first created. */
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mPickDate = (Button) findViewById(R.id.pickDate);
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
updateDisplay();
}
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
}