1

I'm using two timepickers in the same activity to let the user choose a start time and a stop time for a specific task, I'm using the DialogFragment class that's available in the support library for backward compatibility with older Android versions.

I set the timepickers and they're showing up correctly, but I can't figure out how to get the values the user inputs for both of these timepickers, I don't have any background or experience with implementing dialogs so your guidance with code example is highly appreciated!

Here is my code to create the TimePickerFragment class, created in a seperate file, taken and edited slightly from: http://developer.android.com/guide/topics/ui/controls/pickers.html :

package com.calls.only;

import java.util.Calendar;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class TimePickerFragment extends DialogFragment {

    @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);

        if (!(getActivity() instanceof OnTimeSetListener)) throw new IllegalStateException("Activity should implement OnTimeSetListener!");
            OnTimeSetListener timeSetListener =  (OnTimeSetListener) getActivity();

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), timeSetListener, hour, minute, false);
    }
}

Inside My MainActivity:

package com.calls.only;
import java.util.Calendar;
import java.util.TimeZone;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.DialogFragment;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener {

    public void InputStartTime(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }

    public void InputEndTime(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Log.i("TimePicker", "Time picker set!");
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Any ideas on how to implement two timepickers and differentiate between their inputs by adding something to the code above?

blackpanther
  • 10,998
  • 11
  • 48
  • 78
naz89
  • 71
  • 5
  • 12
  • i can show u an Activity where i hv implemented it. Will it be fine? – Parijat Bose Apr 10 '13 at 19:28
  • yes sure, i'll try it and maybe get an idea of how it works in case it didn't work for me – naz89 Apr 10 '13 at 19:29
  • MH. answered this question here: http://stackoverflow.com/questions/15915318/timepicker-ontimeset-not-being-called his answer is marked as the correct answer for the question. – naz89 Apr 10 '13 at 20:30

3 Answers3

1

I have just implemented a similar projecte. I used an inner DialogFragment to show DatePickerDialog and a flag to detect which EditText is clicked.
You can get a sample on my github

MainActivity.java

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText mStartTime;
private EditText mEndTime;

private DatePickerDialogFragment mDatePickerDialogFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mStartTime = (EditText) findViewById(R.id.start_date);
    mEndTime = (EditText) findViewById(R.id.end_date);
    mDatePickerDialogFragment = new DatePickerDialogFragment();

    mStartTime.setOnClickListener(this);
    mEndTime.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.start_date) {
        mDatePickerDialogFragment.setFlag(DatePickerDialogFragment.FLAG_START_DATE);
        mDatePickerDialogFragment.show(getSupportFragmentManager(), "datePicker");
    } else if (id == R.id.end_date) {
        mDatePickerDialogFragment.setFlag(DatePickerDialogFragment.FLAG_END_DATE);
        mDatePickerDialogFragment.show(getSupportFragmentManager(), "datePicker");
    }
}

public class DatePickerDialogFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {
    public static final int FLAG_START_DATE = 0;
    public static final int FLAG_END_DATE = 1;

    private int flag = 0;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void setFlag(int i) {
        flag = i;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, monthOfYear, dayOfMonth);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (flag == FLAG_START_DATE) {
            mStartTime.setText(format.format(calendar.getTime()));
        } else if (flag == FLAG_END_DATE) {
            mEndTime.setText(format.format(calendar.getTime()));
        }
    }
}

activity_main.xml

<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.edinstudio.app.samples.datepicker.MainActivity">

<EditText
    android:id="@+id/start_date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:hint="Please pick a date" />

<EditText
    android:id="@+id/end_date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/start_date"
    android:focusable="false"
    android:hint="Please pick a date" />
</RelativeLayout>
ishitcno1
  • 713
  • 9
  • 10
0

Instead of implementing TimePickerDialog.OnTimeSetListener in the Activity, provide it to the fragment in the constructor. That way each instance can do something different.

So you'll use it like:

  frag1 = new TimePickerFragment(new TimePickerDialog.OnTimeSetListener() { /* Your implementation*/ });
dmon
  • 30,048
  • 8
  • 87
  • 96
  • MH. answered this question here: http://stackoverflow.com/questions/15915318/timepicker-ontimeset-not-being-called thanks for your answer though! – naz89 Apr 10 '13 at 20:31
  • Strange... that answer still doesn't differentiate between fragments, no? – dmon Apr 10 '13 at 21:14
  • Maybe not in the sense you are talking about, however, I was looking for a way to get the input from two different timepickers, so that answer does the job. – naz89 Apr 11 '13 at 01:51
0

Activity where onClick() of an editText a dialog appears with timepicker

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if ((v.getId() == R.id.edtTime)) {

        final Dialog dialog = new Dialog(AddTimeActivity.this);
        dialog.setContentView(R.layout.add_time_dialog);
        Button mSave = (Button) dialog.findViewById(R.id.btnSave);
        mSave.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                TimePicker timePicker = (TimePicker) dialog
                        .findViewById(R.id.timePicker1);
                timePicker.clearFocus();
                hourSelect = timePicker.getCurrentHour();
                minuteSelect = timePicker.getCurrentMinute();

                if (hourSelect == 0) {
                    tt = "AM";
                    hourSelect = 12;
                } else if (hourSelect > 0 && hourSelect < 12) {
                    tt = "AM";
                } else if (hourSelect == 12) {
                    tt = "PM";
                } else {
                    tt = "PM";
                    hourSelect = hourSelect - 12;
                }
                timeSelect = hourSelect;
                edtTime.setText(new         StringBuilder().append(timeSelect)
                          .append(":").append(pad(minuteSelect)).append(tt));
                dialog.dismiss();

            }
        });
        dialog.show();
    }

add_time_dialog.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:gravity="center"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select Time" />

<TimePicker
    android:id="@+id/timePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center" />

<Button
    android:id="@+id/btnSave"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:text=" Save " />

</LinearLayout>
Parijat Bose
  • 380
  • 1
  • 6
  • 22
  • This will not work on all android versions since i'm using the support library, however thanks to MH. for answering this question on my previous question: http://stackoverflow.com/questions/15915318/timepicker-ontimeset-not-being-called – naz89 Apr 10 '13 at 20:30