I've been trying to make a DatePickerDialog and TimePickerDialog to show a title on top but nothing worked so far. I tried using setTitle before showing the date/time pickers and also tried setCustomTitle.
Here is my Dialog class that I use to show date picker and time picker which is based on this answer.
DateTimePickerDialog.java
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Calendar;
public class DateTimePicker extends DatePickerDialog {
#NonNull
private Calendar calendar = Calendar.getInstance();
#Nullable
private DatePickerDialog datePickerDialog;
#Nullable
private TimePickerDialog timePickerDialog;
private String pickerTitle;
private TextView customTitle;
public DateTimePicker(Context context, OnDateSetListener dateListener, int year, int monthOfYear, int dayOfMonth) {
super(context, dateListener, year, monthOfYear, dayOfMonth);
}
public setPickerTitle(String title, TextView view){
this.pickerTitle = title;
this.customTitle = view;
}
public void showDialog(#NonNull Context context, long time) {
calendar.setTimeInMillis(time);
closeDialogs();
showDatePicker(context);
}
private void closeDialogs() {
if (datePickerDialog != null) {
datePickerDialog.dismiss();
datePickerDialog = null;
}
if (timePickerDialog != null) {
timePickerDialog.dismiss();
timePickerDialog = null;
}
}
private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
timePicker(view.getContext());
dateListener.onDateSet(view, year, month, dayOfMonth);
}
};
private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
timeListener.onTimeSet(view, hourOfDay, minute);
}
};
private void showDatePicker(#NonNull Context context) {
datePickerDialog = new DatePickerDialog(context,
dateSetListener,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.setTitle(this.pickerTitle);
datePickerDialog.show();
}
private void timePicker(#NonNull Context context) {
timePickerDialog = new TimePickerDialog(context,
timeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true);
timePickerDialog.setCustomTitle(this.customTitle);
timePickerDialog.show();
}
}
And this is how I'm using it in my Fragment:
private void onDateTimeClick(){
DateTimePicker dateTimePicker = new DateTimePicker(getContext(), onDateSetListener, Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
TextView view = new TextView(getContext());
view.setText("Custom title");
dateTimePicker.setPickerTitle("My title", view);
dateTimePicker.showDialog(Objects.requireNonNull(getContext()), Calendar.getInstance().getTimeInMillis());
}
I tried overriding setTitle method as mentioned here, used setTitle and setCustomTitle individually and combined, and I went through all I could find on SO but nothing worked so far. When I debugged my code, I noticed that when setTitle is called, the cursor jumps to setTitle on AlertDialog.java then to the below method of PhoneWindow.java where mViewTitle is null. I think this may be it but couldn't figure out how to fix it.
public void setTitle(CharSequence title, boolean updateAccessibilityTitle) {
if (mTitleView != null) {
mTitleView.setText(title);
} else if (mDecorContentParent != null) {
mDecorContentParent.setWindowTitle(title);
}
mTitle = title;
if (updateAccessibilityTitle) {
WindowManager.LayoutParams params = getAttributes();
if (!TextUtils.equals(title, params.accessibilityTitle)) {
params.accessibilityTitle = TextUtils.stringOrSpannedString(title);
if (mDecor != null) {
// ViewRootImpl will make sure the change propagates to WindowManagerService
ViewRootImpl vr = mDecor.getViewRootImpl();
if (vr != null) {
vr.onWindowTitleChanged();
}
}
dispatchWindowAttributesChanged(getAttributes());
}
}
}
Thanks for any help
You need to set a theme when creating the DatePickerDialog and the title will show up.
new DatePickerDialog(
context,
android.R.style.Theme_Material_Light_Dialog,
...
))
Related
I've *been able to make a customized calendar that can hold events but I cant help but notice the "1" under the days of the calendar
[Here's the picture][1]
[1]: https://i.stack.imgur.com/tUppW.png
Here is the code for my customized calendar:
package com.example.projecttweeta;
import android.app.TimePickerDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import static android.icu.text.DateFormat.MONTH;
import static android.icu.text.DateFormat.YEAR;
public class CustomCalenderView extends LinearLayout {
// Created instances for the code to run...
ImageButton NextButton, PreviousButton;
TextView CurrentDate;
GridView gridView;
private DBOpenHelper dbOpenHelper;
public static final int MAX_CALENDER_DAYS = 42;
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
Context context;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM", Locale.ENGLISH);
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.ENGLISH);
SimpleDateFormat taskDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
GridAdapter myGridAdapter;
AlertDialog alertDialog;
List<Date> dates = new ArrayList<>();
List<Tasks> tasksList = new ArrayList<>();
public CustomCalenderView(Context context) {
super(context);
}
public CustomCalenderView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
InitializeLayout();
setUpCalender();
PreviousButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, -1);
setUpCalender();
}
});
NextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, 1);
setUpCalender();
}
});
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// an alert dialog; might change later...
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
View addView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.set_reminder_layout, null);
EditText taskTitle = addView.findViewById(R.id.title_edit_text);
EditText taskDescription = addView.findViewById(R.id.description_edit_text);
TextView taskTime = addView.findViewById(R.id.time_edit_text_view);
taskTime.setInputType(InputType.TYPE_NULL);
// Find a way to include settings or something around here
Button saveTask = addView.findViewById(R.id.save_button);
taskTime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(addView.getContext(),
R.style.DatePickerTheme, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar1.set(Calendar.MINUTE, minute);
calendar1.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
String plannedTime = sdf.format(calendar1.getTime());
CurrentDate.setText(plannedTime);
}
}, hours, minute, false);
timePickerDialog.show();
}
});
String date = taskDateFormat.format(dates.get(position));
String month = monthFormat.format(dates.get(position));
String year = yearFormat.format(dates.get(position));
saveTask.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveTaskEvent(taskTitle.getText().toString(),
taskDescription.getText().toString(), taskTime.getText().toString(), date, month, year);
setUpCalender();
alertDialog.dismiss();
}
});
builder.setView(addView);
alertDialog = builder.create();
alertDialog.show();
}
});
}
public CustomCalenderView(Context context, #Nullable AttributeSet attrs, int defStyleAttr, Context
context1) {
super(context, attrs, defStyleAttr);
}
private void saveTaskEvent(String title, String description, String time, String date, String Mmonth, String mYear) {
dbOpenHelper = new DBOpenHelper(context);
SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
dbOpenHelper.SaveTask(title, description, time, date, Mmonth, mYear, database); // supposed to put database here but... meh
dbOpenHelper.close();
Toast.makeText(context, "Task saved", Toast.LENGTH_SHORT).show();
}
private void InitializeLayout() {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.calender_layout, this);
NextButton = view.findViewById(R.id.next_btn);
PreviousButton = view.findViewById(R.id.prev_btn);
CurrentDate = view.findViewById(R.id.current_date);
gridView = view.findViewById(R.id.gridview);
}
private void setUpCalender() {
String currentDate = simpleDateFormat.format(calendar.getTime());
CurrentDate.setText(currentDate);
dates.clear();
Calendar monthCalender = (Calendar) calendar.clone();
monthCalender.set(Calendar.DAY_OF_MONTH, 1);
int firstDayOfMonth = monthCalender.get(Calendar.DAY_OF_WEEK) - 1;
monthCalender.add(Calendar.DAY_OF_MONTH, -firstDayOfMonth);
collectTasksPerMonth(monthFormat.format(calendar.getTime()), yearFormat.format(calendar.getTime()));
while (dates.size() < MAX_CALENDER_DAYS) {
dates.add(monthCalender.getTime());
monthCalender.add(Calendar.DAY_OF_MONTH, 1);
}
myGridAdapter = new GridAdapter(context, dates, calendar, tasksList);
gridView.setAdapter(myGridAdapter);
}
private void collectTasksPerMonth(String month, String year) {
tasksList.clear();
dbOpenHelper = new DBOpenHelper(context);
SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
Cursor cursor = dbOpenHelper.ReadTasksPerMonth(month, year, database);
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex(DBStructure.TITLE));
String description = cursor.getString(cursor.getColumnIndex(DBStructure.DESCRIPTION));
String time = cursor.getString(cursor.getColumnIndex(DBStructure.TIME));
String date = cursor.getString(cursor.getColumnIndex(DBStructure.DATE));
String Mmonth = cursor.getString(cursor.getColumnIndex(DBStructure.DMONTH));
String mYear = cursor.getString(cursor.getColumnIndex(DBStructure.DYEAR));
// Tasks tasks = new Tasks(title,description,time,date,month,year);
Tasks maketask = new Tasks(title, description, time, date, Mmonth, mYear);
tasksList.add(maketask);
}
cursor.close();
dbOpenHelper.close();
}
}
And here is my grid adapter...
package com.example.projecttweeta;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class GridAdapter extends ArrayAdapter {
List<Date> dates;
Calendar currentDate;
List<Tasks> tasks;
LayoutInflater inflater;
public GridAdapter(#NonNull Context context, List<Date> dates, Calendar currentDate, List<Tasks> tasks) {
super(context, R.layout.single_cell_layout); // work on that after this...
this.tasks = tasks;
this.dates = dates;
this.currentDate = currentDate;
inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Date monthDate = dates.get(position);
TextView tv;
Calendar dateCalender = Calendar.getInstance();
dateCalender.setTime(monthDate);
int dayNo = dateCalender.get(Calendar.DAY_OF_MONTH);
int displayMonth = dateCalender.get(Calendar.MONTH) + 1;
int displayYear = dateCalender.get(Calendar.YEAR);
int currentYear = currentDate.get(Calendar.YEAR);
int currentMonth = currentDate.get(Calendar.MONTH) + 1;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.single_cell_layout, parent, false);
}
if (displayMonth == currentMonth && displayYear == currentYear) {
view.setBackgroundColor(Color.parseColor("#60DDED"));
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
TextView day_number = view.findViewById(R.id.calender_day);
TextView task_number = view.findViewById(R.id.task_id);
day_number.setText(String.valueOf(dayNo));
Calendar taskCalender = Calendar.getInstance();
ArrayList<String> arrayList = new ArrayList<>();
// SOLVED!!!!
for (int i = 0; i < tasks.size(); i++) {
taskCalender.setTime(convertStringToDate(tasks.get(i).getDATE()));
if (dayNo == taskCalender.get(Calendar.DAY_OF_MONTH) && displayMonth == taskCalender.get(Calendar.MONTH) + 1 && displayYear == taskCalender.get(Calendar.YEAR)) {
arrayList.add(tasks.get(i).getTITLE());
task_number.setText(arrayList.size() + " Tasks");
}
}
return view;
}
#Override
public int getCount() {
return dates.size();
}
private Date convertStringToDate(String taskDate) {
java.text.SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd", Locale.ENGLISH);
Date date = null;
try {
date = format.parse(taskDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return date;
}
#Override
public int getPosition(#Nullable Object item) {
return dates.indexOf(item);
}
#Nullable
#Override
public Object getItem(int position) {
return dates.get(position);
}
}
Please I'd need a response ; I'm on a deadline. Thanks a lot!!
Attempting to change the theme of timepicker but unsure how its done. The code below works fine, just would like a different look (something like this.
Is it possible to change the below code by adding one the these themes
THEME_DEVICE_DEFAULT_DARK
THEME_DEVICE_DEFAULT_LIGHT
THEME_HOLO_DARK
THEME_HOLO_LIGHT
THEME_TRADITIONAL
import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Private members of the class */
private TextView displayTime;
private Button pickTime;
private int pHour;
private int pMinute;
/** This integer will uniquely define the dialog to be used for displaying time picker.*/
static final int TIME_DIALOG_ID = 0;
/** Callback received when the user "picks" a time in the dialog */
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
pHour = hourOfDay;
pMinute = minute;
updateDisplay();
displayToast();
}
};
/** Updates the time in the TextView */
private void updateDisplay() {
displayTime.setText(
new StringBuilder()
.append(pad(pHour)).append(":")
.append(pad(pMinute)));
}
/** Displays a notification when the time is updated */
private void displayToast() {
Toast.makeText(this, new StringBuilder().append("Time choosen is ").append(displayTime.getText()), Toast.LENGTH_SHORT).show();
}
/** Add padding to numbers less than ten */
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Capture our View elements */
displayTime = (TextView) findViewById(R.id.timeDisplay);
pickTime = (Button) findViewById(R.id.pickTime);
/** Listener for click event of the button */
pickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
/** Get the current time */
final Calendar cal = Calendar.getInstance();
pHour = cal.get(Calendar.HOUR_OF_DAY);
pMinute = cal.get(Calendar.MINUTE);
/** Display the current time in the TextView */
updateDisplay();
}
/** Create a new dialog for time picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, pHour, pMinute, false);
}
return null;
}
}
try using this class:
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
// Get a Calendar instance
final Calendar calendar = Calendar.getInstance();
// Get the current hour and minute
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_LIGHT
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,this,hour,minute,false);
// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_DARK
TimePickerDialog tpd2 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,hour,minute,false);
// TimePickerDialog Theme : THEME_HOLO_DARK
TimePickerDialog tpd3 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_DARK,this,hour,minute,false);
// TimePickerDialog Theme : THEME_HOLO_LIGHT
TimePickerDialog tpd4 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,hour,minute,false);
// TimePickerDialog Theme : THEME_TRADITIONAL
TimePickerDialog tpd5 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_TRADITIONAL,this,hour,minute,false);
// Return the TimePickerDialog
return tpd; //return your themed timepicker like tpd2, tpd3 etc..
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
// Do something with the returned time
TextView tv = (TextView) getActivity().findViewById(R.id.tv);
tv.setText("HH:MM\n" + hourOfDay + ":" + minute);
}
}
use it in your Activity as:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment = new TimePickerFragment();
// Show the time picker dialog fragment
dFragment.show(getFragmentManager(),"Time Picker");
}
});
I am using this method to read the date from the calendar and display it on the TextView but it only show me 25:10:2015 and it doesn't change when I choose another date. I wrote event to change the date but i don't know what is wrong:
package com.example.user.calendar;
import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView datee=(TextView)findViewById(R.id.textView2);
final Calendar c=Calendar.getInstance();
final int year =c.get(Calendar.YEAR);
final int month =c.get(Calendar.MONTH);
final int day =c.get(Calendar.DAY_OF_MONTH);
datee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datepicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
datee.setText(" ");
datee.setText(year + ":" + month + ":" + day);
// dayyy=datee.getText().toString();
}
}, year, month, day);
datepicker.setTitle("select date");
datepicker.show();
}
});
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib = (ImageButton) findViewById(R.id.imageButton1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) findViewById(R.id.editText);
ib.setOnClickListener((View.OnClickListener) this);
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
}
try this I hope its work.
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
When you 'setText' you are using the variables from 'Calendar.getInstance();' which set those variables according to the current day, month, and year. Instead you should be using the variables that are set by the datePicker.
Instead of:
datee.setText(year + ":" + month + ":" + day);
use this:
datee.setText(year + ":" + monthOfYear + ":" + dayOfMonth);
Also, the month returned by Calendar.Month is off by one (10 instead of 11) because the Java Calendar goes from 0 to 11. So you have to add 1 to the month to get the correct number for the current month. But the month value (dayOfMonth) returned by the datePicker should be correct by default.
I have been using this tutorial here to create a time picker. I can select the time fine, but I can't get the time selected to show up in my TextView. Java is not my preferred language so that is probably where I am falling down.
Here is my java code:
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//code from: http://developer.android.com/guide/topics/ui/controls/pickers.html
public void showTimePicker(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user - how!?
}
}
}
In my XML I have the Choose Time button run the showTimePicker method on click like so:
android:onClick="showTimePicker"
I have tried just setting the text field inside the onTimeSet method but I get a nullpointerexception. Then I thought I should initialize it in onCreateDialog but there I don't know how to use findViewById to find the actual text view. I'm sure this is probably simple but I have searched up and down without much luck. Thanks for your help!
you can do it like that:
1) Solution 1 (better):
public class MainActivity extends Activity {
TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = (TextView)findViewById(R.id./*YOUR TEXT VIEW ID*/);
}
//code from: http://developer.android.com/guide/topics/ui/controls/pickers.html
public void showTimePicker(View v) {
DialogFragment newFragment = new TimePickerFragment(resultText);
newFragment.show(getFragmentManager(), "timePicker");
}
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
TextView mResultText;
public TimePickerFragment(TextView textView) {
mResultText = textView;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String time = /*CONVERT YOUR TIME FROM hourOfDay and minute*/;
mResultText.setText(time);
}
}
}
2) Solution 2:
public class MainActivity extends Activity {
public TextView mResultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultText = (TextView)findViewById(R.id./*YOUR TEXT VIEW ID*/);
}
//code from: http://developer.android.com/guide/topics/ui/controls/pickers.html
public void showTimePicker(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String time = /*CONVERT YOUR TIME FROM hourOfDay and minute*/;
mResultText.setText(time);
}
}
}
You can actually use findViewById, as with getActivity() your fragment gets access to the activity it is running in and thus to the views inside the activity.
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView textView = (TextView) getActivity().findViewById(R.id.my_text_view);
textView.setText(String.format("%02d", hourOfDay), String.format("%02d", minute);
}
This simple solution should be preferred over passing a reference to the TextView to the fragment, as this reference will be lost on reinstantiation of the fragment (see comment).
I want to create a TimePickerDialog using FragmentDialog and exchange data between my fragment and the TimePickerDialog . I already created a DatePickerDialog but I don't know how to create a TimePickerDialog . I want that when the user click the button in my fragment TimePickerDialog appear .
This is how I create The DatePickerDialog :
import java.util.Calendar; import java.util.Date; import
java.util.GregorianCalendar;
import android.app.Activity; import android.app.AlertDialog; import
android.app.Dialog; import android.content.DialogInterface; import
android.content.Intent; import android.os.Bundle; import
android.support.v4.app.DialogFragment; import android.view.View;
import android.widget.DatePicker; import
android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "criminalintent.DATE";
Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date)getArguments().getSerializable(EXTRA_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker)v.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month, int day) {
mDate = new GregorianCalendar(year, month, day).getTime();
// update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK);
}
})
.create();
} }
CrimeFragment
import java.util.Date; import java.util.UUID;
import android.app.Activity; import android.content.Intent; import
android.os.Bundle; import android.support.v4.app.Fragment; import
android.support.v4.app.FragmentManager; import android.text.Editable;
import android.text.TextWatcher; import android.view.LayoutInflater;
import android.view.View; import android.view.ViewGroup; import
android.webkit.WebView.FindListener; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener; import
android.widget.EditText;
public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID = "criminalintent.CRIME_ID";
private static final String DIALOG_DATE = "date";
private static final int REQUEST_DATE = 0;
Crime mCrime;
EditText mTitleField;
Button mDateButton;
CheckBox mSolvedCheckBox;
Button mTime;
String time;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
public void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
public void updateTime() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before, int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count, int after) {
// this space intentionally left blank
}
public void afterTextChanged(Editable c) {
// this one too
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTime = (Button) v.findViewById(R.id.crime_time);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_DATE) {
Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
} }
Now I want to create a TimePickerDialog .
public class DialogFragmentTimePicker extends DialogFragment implements OnTimeSetListener {
public static final String ARG_HOUR = "hour";
public static final String ARG_MINUTE = "minute";
private OnTimeSetListener mListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
int hour, minute;
if (getArguments() != null) {
hour = getArguments().getInt(ARG_HOUR);
minute = getArguments().getInt(ARG_MINUTE);
} else {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
}
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
public void setOnTimeSetListener(OnTimeSetListener listener) {
mListener = listener;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (mListener != null) {
mListener.onTimeSet(view, hourOfDay, minute);
}
}
}