Time Picker Fragments Differentiation - android

I have run into a problem where my app is properly building and buttons are working as expect, but the text field I am editing with two time picker fragments is being edited by both the start time picker and end time picker.
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_start = (Button) findViewById(R.id.start_picker_button);
button_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker1 = new TimePickerStartFragment();
timePicker1.show(getSupportFragmentManager(),"time picker start");
}
});
Button button_end = (Button) findViewById(R.id.end_picker_button);
button_end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker2 = new TimePickerEndFragment();
timePicker2.show(getSupportFragmentManager(),"time picker end");
}
});
}
#Override
public void onTimeSet(TimePicker TimePickerStartFragment, int hourOfDay, int minute) {
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Hour: " + hourOfDay + " " + "Minute: " + minute);
My application looks like two buttons, one for a start time fragment and the other for an end time fragment. I have two seperate time picker fragment java files. However, when I set the end time fragment it still modifies the start time text. I want to have the start time picker only modify the start time text and the end time picker modify the end time text.
To further clarify when the select start time button is pressed TimePickerStratFragment is opened and a time is selected, this modifies a text field called textView. However when the time end button fragment is selected it also modifies the text view. I want the time end button to not modify the text view.

Add a String value to check which time picker is opened, because onTimeSet is fired for both fragments use something like this
String timeTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_start = (Button) findViewById(R.id.start_picker_button);
button_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeTag = "from";
DialogFragment timePicker1 = new TimePickerStartFragment();
timePicker1.show(getSupportFragmentManager(),"time picker start");
}
});
Button button_end = (Button) findViewById(R.id.end_picker_button);
button_end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeTag = "to";
DialogFragment timePicker2 = new TimePickerEndFragment();
timePicker2.show(getSupportFragmentManager(),"time picker end");
}
});
}
#Override
public void onTimeSet(TimePicker TimePickerStartFragment, int hourOfDay, int minute) {
if(Objects.equals(timeTag, "from")) {
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Hour: " + hourOfDay + " " + "Minute: " + minute);
}
if(Objects.equals(timeTag, "to")) {
}
}

Related

Android: How to set time from time picker in two different EditText fields (start/end)?

I am trying to get the time when the user clicks on the EditText StartTime and EndTime. The problem is that I don't know how to distinguish the EditTexts at the TimePickerFragment. Any help, please?
public void initializeTime () {
startTimeEditText = (EditText) findViewById(R.id.startTimeEditText);
startTimeEditText.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(getSupportFragmentManager(),"TimePicker");
}
});
endTimeEditText = (EditText) findViewById(R.id.endTimeEditText);
endTimeEditText.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(getSupportFragmentManager(),"TimePicker");
}
});
}
TimePickerFragment.java:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
EditText startTimeEditText = (EditText) getActivity().findViewById(R.id.startTimeEditText);
EditText endTimeEditText = (EditText) getActivity().findViewById(R.id.endTimeEditText);
flag = getArguments().getString("Flag");
Log.v(TAG,flag);
Toast.makeText(getActivity(), "Toast"+flag, Toast.LENGTH_LONG).show();
if (startTimeEditText.isActivated()){
startTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
else if (endTimeEditText.isActivated()){
endTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
}
TimePickerFragment should not mess with the layout of the rest of the Activity: the best way here is to pass a listener to the TimePickerFragment. Take a look at TimePicker.setOnTimeChangedListener(...), I know it's not a Fragment, but the idea is the same.
Another solution is to use an event bus (for example including the EventBus library) and posting a new event when the user select a date: in this way any component of your app can subscribe to this event and act accordingly.

Getting time using time picker and show it using Toast, code doesn't work

I was trying a simple code which shows time selected using Toast and time picker but nothing happens and there was no errors, the same also happens in date picker.
Here is the code:
public class MainActivity extends ActionBarActivity {
TimePicker tP;
public void clickMe(View V){
Toast.makeText(this,"Time Selected: " + (tP.getCurrentHour()) + ":" + tP.getCurrentMinute(),Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tP = (TimePicker)findViewById(R.id.timePicker);
}
I've only made a time picker in the layout and an onclick:clickMe.
Note: This was supposed to work because I've taken this code from an instructor.
Edit:
Here is layout:
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/timePicker"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="clickMe" />
Edit 2
Sorry, maybe i should have elaborated my question:
Why isn't my code not working?
for now i don't need the solution i just want the reason why this didn't work?
thanks.
EDIT 2: Btw make sure you press part that shows selected time, and the toast will pop up
EDIT
add following line into XML if you want it to be clickable:
android:clickable="true"
=======================================================================
Alternative solution:
Try adding OnClickListener in onCreate method, just after you call findViewById, and remove onClick attribute from the layout..
tm = (TimePicker) findViewById(R.id.timepciker_id);
tm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(this,"Time Selected: " + (tP.getCurrentHour()) + ":" + tP.getCurrentMinute(),Toast.LENGTH_LONG).show();
}
});
Try to use setOnTimeChangedListener instead of onClick as follows:
tP = (TimePicker) findViewById(R.id.timePicker);
tP.setOnTimeChangedListener( new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(getApplicationContext(),String.valueOf(hourOfDay) + " "+ String.valueOf(minute),Toast.LENGTH_LONG).show();
}
});
You can try to use
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hour, int minute) {
setTime(timePicker, hour, minute);
}
}
and call this as
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getChildFragmentManager(), "timePicker");

Android - Add new buttons in listview dynamically

I've a Listview with two linear layouts and there is one button add new row . When i click add new row button i want to create new row of buttons dynamically. After that click on that created button i want to show an time picker dialog . When user click set time button i want to set that time in that button. My problem is All the buttons(with different id) are added fine and when click that button time picker dialog was pop up. But after click set time button the time will not set . How can i add this time to the button. How can i handle this button ?
It is my piece of code inside of listview onscroll listener
final LinearLayout l1 = LinearLayout) List_Layout.getChildAt(0);
LinearLayout l12 = (LinearLayout) List_Layout.getChildAt(1);
final Button button = new Button(getApplicationContext());
final Button button1 = new Button(getApplicationContext());
add_button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
button.setLayoutParams(lparams);
button1.setLayoutParams(lparams);
button.setId(0);
button1.setId(1);
l1.addView(button, lparams);
l12.addView(button1, lparams);
}
}
button.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
showDialog(TIME_DIALOG_ID);
}
}
button1.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.e("tag 1", button1.getTag()+"");
showDialog(TIME_DIALOG_ID);
}
});
Rest of the codes for timepicker dialog is works fine
It's just sample code
Please anyone help me get out from this riddle.
Edit:
static final int TIME_DIALOG_ID = 998;
private int hour;
private int minute;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
}
}
You need to set text of button or button1 to the time that was actually picked by the user. To do so, code some button.setText(<formatted time>) in the timePickerListener.
Here's some line of code, I use to format date and time from a java.util.Date object:
Date date = new Date();
java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(context);
java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
button.setText(String.format("%s %s", dateFormat.format(date), timeFormat.format(date)));
In your case of the time picker you can just format the selected values into a string:
button.setText(String.format("%02d:%02d", selectedHour, selectedMinute));

Getting Values from DatePicker and TimePicker

I have 2 datepickers and 2 timepickers on a screen and also a submit button. The user selects the start date, start time, end date, and end time. The program then takes these values and stores them into variables, however the variables only return the default values for these controls. Is there anyway to get the updated value from each of these controls?
My code looks like this for the edit screen:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.editscreen);
timepickerStart = (TimePicker)findViewById(R.id.timePicker1);
timepickerEnd = (TimePicker)findViewById(R.id.timePicker2);
datepickerStart = (DatePicker)findViewById(R.id.datePicker1);
datepickerEnd = (DatePicker)findViewById(R.id.datePicker2);
submitbutton = (Button)findViewById(R.id.submit);
locationText = (EditText)findViewById(R.id.locationText);
eventText = (EditText)findViewById(R.id.eventText);
}
public void DateStart(View v)
{
GlobalVariables.datepickerYearStart = datepickerStart.getYear();
GlobalVariables.datepickerMonthStart = datepickerStart.getMonth();
GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth();
}
public void DateEnd(View v)
{
GlobalVariables.datepickerYearEnd = datepickerEnd.getYear();
GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth();
GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth();
}
public void TimeStart(View v)
{
GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour();
GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute();
}
public void TimeEnd(View v)
{
GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour();
GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute();
}
public void submitClicked(View v)
{
startActivity(new Intent(this, AddToCalendar.class));
}
Rewrite
Looking at your current code, let's stick with the various get methods from DatePicker and TimePicker. However you never call DateStart() or any of the others, they look like you have them set up for an OnClickListener... Regardless, try this:
public void submitClick(View v) {
DateStart(null);
TimeStart(null);
DateEnd(null);
TimeEnd(null);
// Do what you please your GlobalVariables
}
Though I might leave out the multiple GlobalVariables and store one long value for each date/time:
public void submitClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(),
datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(),
timepickerStart.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
// And similar approach for the end time, then use them however you please
}
You need to set a listener to your DatePicker:
DatePicker picker = new DatePicker(this);
picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//set the value of the variable here
}
});

How to have data from dialog box to listview in android 2.1?

all
i have created listview dynamically.now i want to change the name of listview/listitems or i want to retrieve content below each row but the content is coming from dialogbox.is it possible to have data from dialogbox in listview?How to achieve this??can any one guide or give some sample code of the same?
Thanks in Advance--
public class Tdate extends Activity
{
private ListView lView;
private String lv_items[] = { "Birth_Date", "Anniversary_Date", "Joining_Date","Meeting_Date","Appraisal_Date","Anniversary_Date", "Joining_Date","Meeting_Date","Appraisal_Date"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tdate);
Button customdate = (Button)findViewById(R.id.customdate);
lView = (ListView) findViewById(R.id.ListView01);
lView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
showDateTimeDialog();
}
});
}
private void showDateTimeDialog()
{
// Create the dialog
final Dialog mDateTimeDialog = new Dialog(this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
// Check is system is set to use 24h time (this doesn't seem to work as expected though)
final String timeS = android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.TIME_12_24);
final boolean is24h = !(timeS == null || timeS.equals("12"));
// Update demo TextViews when the "OK" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.clearFocus();
((TextView) findViewById(R.id.Date)).setText(mDateTimePicker.get(Calendar.YEAR) + "/" + (mDateTimePicker.get(Calendar.MONTH)+1) + "/"
+ mDateTimePicker.get(Calendar.DAY_OF_MONTH));
if (mDateTimePicker.is24HourView()) {
((TextView) findViewById(R.id.Time)).setText(mDateTimePicker.get(Calendar.HOUR_OF_DAY) + ":" + mDateTimePicker.get(Calendar.MINUTE));
} else {
((TextView) findViewById(R.id.Time)).setText(mDateTimePicker.get(Calendar.HOUR) + ":" + mDateTimePicker.get(Calendar.MINUTE) + " "
+ (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
}
mDateTimeDialog.dismiss();
}
});
// Cancel the dialog when the "Cancel" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
mDateTimePicker.reset();
}
});
// Setup TimePicker
mDateTimePicker.setIs24HourView(is24h);
// No title on the dialog window
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
// Display the dialog
mDateTimeDialog.show();
}
}

Categories

Resources