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).
Related
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,
...
))
Since i started programing with java on android projects, i didn't have problems where it says: Non static field cannot be referenced from a static context.
This is my code:
package com.esmad.pdm.friendlymanager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import java.util.Calendar;
import android.media.Image;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
public class NewMatch extends AppCompatActivity {
ImageView questionMark;
RadioGroup radioGroup;
EditText gameEventNameTxt;
TextInputLayout textInputLayout;
TextView dateHourTxt;
public static boolean changedData = false;
public static boolean changedHour = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_match);
questionMark = (ImageView) findViewById(R.id.questionMark);
questionMark.setClickable(true);
gameEventNameTxt = (EditText)findViewById(R.id.gameEvent);
textInputLayout = (TextInputLayout)findViewById(R.id.textInputLayout);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
dateHourTxt = (TextView)findViewById(R.id.dateHour);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
if (checkedId == R.id.event) {
textInputLayout.setHint("Event name");
}
else{
textInputLayout.setHint("Match name");
}
}
});
}
public void imageClick(View view) {
Log.d("builderH","im in the builder");
AlertDialog.Builder builder = new AlertDialog.Builder(NewMatch.this);
builder.setTitle("What is a event?");
builder.setMessage("You can create a Event and a game, a Event is a list of games that can be repeated without the need to create every week a new game!");
builder.setCancelable(false);
builder.setPositiveButton("I got it!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#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) {
changedHour = true;
if(changedHour && changedData){
dateHourTxt
}
}
}
public void hourPicker(View view){
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
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) {
changedData = true;
}
}
public void datePicker(View view){
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
as you guys can see above i changed some data to static at initialization, but in other activities i didn't need to do that, and the same error happens for my dateHourTxt inside my onTimeSet method :S
You guys know why this is happening?
You are referencing dateHourTxt from a completely separate class, one that does not contain dateHourTxt.
Your onTimeSet() method is in TimePickerFragment. That is a static class. While its lines physically are inside of NewMatch, it has no access to regular fields on NewMatch. TimePickerFragment could just as easily be a separate Java class, in its own file. In fact, until you gain a bit more experience with Java, I recommend you do just that, to help you better visualize the separation between classes.
If you want TimePickerFragment to work with NewMatch, you need to do so using typical techniques, such as using getActivity() in the fragment to get at the NewMatch instance, so you can call methods on it.
When you make nested class static, it no longer has access to the outer class non static fields. It can access only static fields. In you example solution is to use Fragment.getActivity method to access NewMatch. It should look as follows,
if(changedHour && changedData){
if (getActivity() != null && getActivity() instanceof NewMatch) {
((NewMatch)getActivity()).dateHourTxt = ...
}
}
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 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);
}
}
}
How do I make this time picker set the edittext box with the time that the TimePickerDialog set?
package com.example.d;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
int hour,min;
//static final int TIME_DIALOG_ID=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
//Do stuff here
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR);
int min=c.get(Calendar.MINUTE);
showTimeDialog(v, hour, min);
}
});
}
OnTimeSetListener timeSetListener;
public void showTimeDialog(View v, int hour, int min)
{
(new TimePickerDialog(this, timeSetListener, hour, min, true)).show();
//how do I make this time picker set the edittext box with the time that the TimePickerDialog set
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:width="320px">
<requestFocus />
</EditText>
</RelativeLayout>
public class MainActivity extends Activity {
int hour = -1, min = -1;
static final int TIME_DIALOG_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
// Do stuff here
if (hour == -1 || min == -1) {
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
min = c.get(Calendar.MINUTE);
}
showTimeDialog(v, hour, min);
}
});
}
public void showTimeDialog(View v, int hour, int min) {
(new TimePickerDialog(MainActivity.this, timeSetListener, hour, min,
true)).show();
}
public TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
min = minute;
EditText et = (EditText) findViewById(R.id.editText1);
et.setText(hour + " : " + min);
}
};
}
You can do it in onTimeSetListener like this
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
setTimeEditText.setText(hour + ":" + minute);
}
};
You have to creat an instance of OnTimeSetListener and in it's onTimeSet method you have the selected hour and minute.