set the edittext box with the time that the TimePickerDialog set - java

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.

Related

Android: time picker in a dialog

I tried to modify this time picker I found here on stackoverflow and placed it in a dialog in my application. When I try to pick the time the result is not what I setted but it is the time of the device, so the time isn't set well. The function TimeSetting is used to call the time picker. I tryed to make it start from zero and take the right time but with no result. Can someone help me find out where the error is?
here is the ExampleDialog.java file:
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialogFragment;
import com.ikovac.timepickerwithseconds.MyTimePickerDialog;
import com.ikovac.timepickerwithseconds.TimePicker;
import java.util.Calendar;
public class ExampleDialog extends AppCompatDialogFragment {
private EditText textInputNome;
private ExampleDialogListener listener;
private Button positiveButton;
private TextView text_view_timesec;
private Button SetTimeBTN;
private String nome = null;
private int timeInSeconds=-1;
private int hourOfDay;
private int minute;
private int seconds;
/*for MainActivity*/
public interface ExampleDialogListener {
boolean applyProgram(String nome);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
textInputNome = view.findViewById(R.id.tiCrea);
SetTimeBTN=view.findViewById(R.id.btn_SetTime);
text_view_timesec=view.findViewById(R.id.textView3);
textInputNome.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
TimeSetting();
}
#SuppressLint("SetTextI18n")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
nome =textInputNome.getText().toString().trim();
TimeSetting();
}
#Override
public void afterTextChanged(Editable s) {
TimeSetting();
}
});
builder.setView(view);
builder.setTitle("Nome programma");
builder.setNegativeButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nome = textInputNome.getText().toString().trim();
listener.applyProgram(nome);
}
});
Dialog dialog = builder.create();
return dialog;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void onStart() {
super.onStart();
AlertDialog d = (AlertDialog) getDialog();
if (d != null ) {
positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setEnabled(false);
}
}
private void TimeSetting(){
SetTimeBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Btn clicked", Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
MyTimePickerDialog mTimePicker = new MyTimePickerDialog(getContext(), new MyTimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute, int seconds) {
SetTimeBTN.setText(getString(R.string.time) + String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", seconds));
}
}, hourOfDay=c.get(Calendar.HOUR_OF_DAY), minute=c.get(Calendar.MINUTE), seconds=c.get(Calendar.SECOND), true);
timeInSeconds = ((hourOfDay * 60 * 60) + (minute * 60) + seconds);
text_view_timesec.setText("hh=" + hourOfDay + " mm=" + minute + " ss=" + seconds + " time tot=" + timeInSeconds);
positiveButton.setEnabled(!nome.isEmpty() && timeInSeconds > 0);
mTimePicker.show();
}
});
}
}
Here is the xml of the dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/time_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/tiCrea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/name"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_SetTime"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:text="#string/clickToSetTime"
android:textAlignment="viewStart"
android:gravity="start" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="here is the time setted from the timepkr" />
</LinearLayout>
in onCreate method change this two lines
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
to
final LinearLayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, (ViewGroup)R.id.time_view");//here the id of the root LinearLayout in the XMl File layout_dialog.

Change Theme of Time Picker - Android

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");
}
});

TimePicker Dialog when clicking EditText

I used this question to get the timepicker when clicking on editext.
Please note that I am putting the code in a fragment.
What i've changed is the following:
Added : Context ctx; to the settime.java
On the line:
SetTime fromTime = new SetTime(chostime,this);
It is telling me : the constructor SetTime(editText, AppointFragment) is not defined.
I’ve tried to change it into :
SetTime fromTime = new SetTime(chostime,getActivity());
When trying to run the application gice me the following error
12-30 18:03:55.120: E/AndroidRuntime(1376): java.lang.NullPointerException
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
First override onActivityCreated() in AppointFragment and then use the getActivity() to create SetTime object.
private SetTime fromTime;
private EditText chosdate, chostime;
...
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
fromTime = new SetTime(chostime,getActivity());
}
The complete code for setting the time using Fragments is below. You can use the same approach for setting the date too.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Fragment to be placed in the activity layout
ChildFragment firstFragment = new ChildFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
//firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, firstFragment).commit();
}
ChildFragment.java (For displaying EditTexts)
public class ChildFragment extends Fragment implements View.OnClickListener, TimePickerFragment.Callback
{
private EditText editText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.child_fragment, null, false);
editText = (EditText) view.findViewById(R.id.time_edit_text);
editText.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view)
{
if(view == editText)
{
TimePickerFragment dialog = new TimePickerFragment();
dialog.setTargetFragment(this, 1); //request code
dialog.show(getFragmentManager(),"dialog");
}
}
#Override
public void onTimeSelected(String time)
{
editText.setText(time);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public interface Callback
{
public void onTimeSelected(String time);
}
private Callback timeCallback;
#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);
timeCallback = (Callback) getTargetFragment();
// 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
timeCallback.onTimeSelected(hourOfDay + ":" + minute + ":00");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameLayout"/>
</RelativeLayout>
child_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_edit_text"/>
</LinearLayout>
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SetTime fromTime = new SetTime(chostime,getActivity());
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
SingleFragmentAcitivity.java
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Appointactivity.java
package com.example.appointapp;
import android.support.v4.app.Fragment;
public class AppointActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new AppointFragment();
}
}
Fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/new_patient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_patient" />
<Button
android:id="#+id/new_appoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_appoint"/>
</LinearLayout>
Fragment_appoint.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/Patients_list"
android:layout_width="117dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/datea_text"
android:layout_width="143dp"
android:layout_height="wrap_content"
android:hint="#string/datea_text_hint" />
<EditText
android:id="#+id/timea_text"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:hint="#string/timea_text_hint" />
<Button
android:id="#+id/savea_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/savea_button" />
</LinearLayout>
Thank you for ur help
i solved the issue using the following code in my fragment:
chostime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
chostime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
Thank you

reading Calendar date

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.

Set TextView to time from TimePicker - Android

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).

Categories