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");
}
});
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,
...
))
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);
}
}
}
I'm building an app that displays a date picker and a time picker on the click of two seperate buttons. I first added in the time picker and it was all working fine, I then proceeded to add the date picker which also works fine. The problem here being that when I added in the date picker, it casused the time picker to stop working. I know they both work and i'm 90% sure it is because of the structure of my code but being that i'm completely new to android and java development I can't work out where i'm going wrong. Any help would be appreciated.
Thanks
Code below:
package com.cam.datetime;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
public class SettingsScreen extends Activity {
private TextView tvDisplayTime;
private TimePicker timePicker1;
private Button btnChangeTime;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
Button change_date_but;
TextView display_txt;
public static final int Date_dialog_id = 1;
// date
private int mYear;
private int mMonth;
private int mDay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_settings);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setCurrentTimeOnView();
addListenerOnButton();
final EditText inputTxt1 = (EditText) findViewById(R.id.conPhoneNum);
Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
change_date_but = (Button) findViewById(R.id.change_button_id);
display_txt = (TextView) findViewById(R.id.display_id);
change_date_but = (Button) findViewById(R.id.change_button_id);
change_date_but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog DPD = new DatePickerDialog(
SettingsScreen.this, mDateSetListener, mYear, mMonth, mDay);
DPD.show();
}
final Calendar c = Calendar.getInstance();{
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);}
void updateDisplay1() {
}
});
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNum1 = inputTxt1.getText().toString();
savenum1(phoneNum1);
//Intent passIntent = new Intent();
//passIntent.putExtra("phoneNum", phoneNum1);
}
});
Button homeButton = (Button) findViewById(R.id.btnHome);
homeButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
startHome();
}
});
Button retTimeBtn = (Button) findViewById(R.id.btnRetTime);
retTimeBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
//returnTime();
}
});
}
//display current time
public void setCurrentTimeOnView() {
tvDisplayTime = (TextView) findViewById(R.id.tvTime);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tvDisplayTime.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
}
private Object pad(int minute2) {
// TODO Auto-generated method stub
return null;
}
public void addListenerOnButton() {
btnChangeTime = (Button) findViewById(R.id.btnChangeTime);
btnChangeTime.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
OnTimeSetListener timePickerListener = null;
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
#Override
#Deprecated
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub
super.onPrepareDialog(id, dialog);
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
}
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();
}
};
private void updateDisplay() {
// TODO Auto-generated method stub
display_txt.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-").append(mDay).append("-")
.append(mYear));
}
public void startHome() {
Intent launchHome = new Intent();
launchHome.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
launchHome.setClassName(this,"com.cam.datetime.MainActivity");
startActivity(launchHome);
}
public void savenum1(String phoneNum1) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Saved " + phoneNum1);
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
dlgAlert.create().show();
}
public void returnTime(){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("", null, "#TU?", null, null);
}
}
Give this a try:
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
public class SettingsScreen extends Activity {
private TextView tvDisplayTime;
private TimePicker timePicker1;
private Button btnChangeTime;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
Button change_date_but;
TextView display_txt;
public static final int Date_dialog_id = 1;
// date
private int mYear;
private int mMonth;
private int mDay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_settings);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final EditText inputTxt1 = (EditText) findViewById(R.id.conPhoneNum);
Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
setCurrentTimeOnView();
//addListenerOnButton();
change_date_but = (Button) findViewById(R.id.change_button_id);
display_txt = (TextView) findViewById(R.id.display_id);
change_date_but = (Button) findViewById(R.id.change_button_id);
Button retTimeBtn = (Button) findViewById(R.id.btnRetTime);
Button homeButton = (Button) findViewById(R.id.btnHome);
btnChangeTime = (Button) findViewById(R.id.btnChangeTime);
change_date_but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
OnDateSetListener mDateSetListener = null;
DatePickerDialog DPD = new DatePickerDialog(
SettingsScreen.this, mDateSetListener, mYear, mMonth, mDay);
DPD.show();
}
final Calendar c = Calendar.getInstance();{
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);}
/*void updateDisplay1() {
}*/
});
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNum1 = inputTxt1.getText().toString();
savenum1(phoneNum1);
//Intent passIntent = new Intent();
//passIntent.putExtra("phoneNum", phoneNum1);
}
});
homeButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
startHome();
}
});
retTimeBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
//returnTime();
}
});
btnChangeTime.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
//display current time
public void setCurrentTimeOnView() {
tvDisplayTime = (TextView) findViewById(R.id.tvTime);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tvDisplayTime.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
}
private Object pad(int minute2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
OnTimeSetListener timePickerListener = null;
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
/*
#Override
#Deprecated
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub
super.onPrepareDialog(id, dialog);
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
}
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();
}
};
private void updateDisplay() {
// TODO Auto-generated method stub
display_txt.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-").append(mDay).append("-")
.append(mYear));
}
*/
public void startHome() {
Intent launchHome = new Intent();
launchHome.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
launchHome.setClassName(this,"com.becatech.gsmzonecontroller.MainActivity");
startActivity(launchHome);
}
public void savenum1(String phoneNum1) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Saved " + phoneNum1);
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
dlgAlert.create().show();
}
public void returnTime(){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("", null, "#TU?", null, null);
}
}
I know this is a basic question, but I'm pretty new to all of this. In the code below, I have this onPause method:
public void onPause(){
super.onPause();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
The input part of input.getWindowToken() doesn't work. I'm guessing that it's because it's not defined/instantiated in the same scope? I think I'm using the right terminology. I'm not even positive that I should be trying to use an EditText object right here either, but it seems whatever I try to do isn't working.
How do I pass something to my onPause() method, or any other method for that matter? Here's all of my code:
package com.example.test_project;
import java.util.Calendar;
import com.example.test_project.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
public class NewWorkout extends Activity {
/** Called when the activity is first created. */
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
private TextView mTimeDisplay;
private Button mTimePicker1;
private int hour;
private int minute;
private String zone;
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 99;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_workout);
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// capture our View elements
mDateDisplay = (TextView) findViewById(R.id.dateOfWorkoutTextView);
mPickDate = (Button) findViewById(R.id.dateOfWorkoutButton);
mTimeDisplay = (TextView) findViewById(R.id.timeOfWorkoutTextView);
mTimePicker1 = (Button) findViewById(R.id.timeOfWorkoutButton);
// add a click listener to the button
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
final Calendar t = Calendar.getInstance();
hour = t.get(Calendar.HOUR_OF_DAY);
minute = t.get(Calendar.MINUTE);
//set the current time into the textview
mTimePicker1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
// updates the date in the TextView
private void updateDisplay() {
StringBuilder string1 = new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" ");
mDateDisplay.setText(string1);
}
// the callback received when the user "sets" the date in the dialog
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();
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
updateTimeDisplay();
}
};
//set current time into textView
private void updateTimeDisplay() {
if(hour > 12){
hour -= 12;
zone = "PM";
}
else
zone = "AM";
if(minute >= 10){
mTimeDisplay.setText(new StringBuilder().append(hour)
.append(":").append(minute).append(" ").append(zone));
}
else
mTimeDisplay.setText(new StringBuilder().append(hour)
.append(":").append("0").append(minute).append(" ").append(zone));
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, timePickerListener, hour, minute, false);
}
return null;
}
public void nameOfWorkout(View view){
AlertDialog.Builder nameOfWorkoutAlert = new AlertDialog.Builder(this);
nameOfWorkoutAlert.setTitle("Enter a Name for This Workout");
// Set an EditText view to get user input
final EditText input = new EditText(this);
nameOfWorkoutAlert.setView(input);
// Prepping the soft keyboard to open with the AlertDialog
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
nameOfWorkoutAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
TextView edit = (TextView) findViewById(R.id.nameOfWorkoutTextView);
edit.setText(value);
imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);
}
});
nameOfWorkoutAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);
}
});
//alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
nameOfWorkoutAlert.show();
//Causing the soft keyboard to open with the AlertDialog
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void onPause(){
super.onPause();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
public void typeOfWorkout(View view){
final String [] items=new String []{"Weight-lifting","Cardio","Mixture"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Select Today's Workout type");
builder.setItems(items, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.typeOfWorkoutTextView);
txt.setText(items[which]);
}
});
builder.show();
}
}
Thanks for the help!
Make it a variable in your class.
public class NewWorkout extends Activity {
private EditText input
...
public void nameOfWorkout(View view){
// Set an EditText view to get user input
input = new EditText(this);
...
}
public void onPause() {
if (input != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
super.onPause();
}
...
}
Well, you can use this as an alternative.
public void onPause()
{
super.onPause();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}