在同一个活动中实现两个TimePickers

时间:2013-04-10 19:21:16

标签: java android dialog datepicker timepicker

我在同一个活动中使用两个timepickers让用户选择特定任务的开始时间和停止时间,我正在使用支持库中提供的DialogFragment类,以便与旧版本的Android版本向后兼容

我设置了timepickers并且它们正确显示,但我无法弄清楚如何获取用户为这两个时间选择器输入的值,我没有任何背景或实施对话框的经验所以你的代码示例的指导非常感谢!

以下是我创建TimePickerFragment类的代码,该类在单独的文件中创建,稍微从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);
    }
}

在我的主要活动中:

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

有关如何实现两个时间戳并通过在上面的代码中添加内容来区分其输入的任何想法?

3 个答案:

答案 0 :(得分:1)

我刚刚实施了类似的项目。我使用内部DialogFragment来显示DatePickerDialog和一个标志来检测单击哪个EditText。
您可以在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>

答案 1 :(得分:0)

不是在Activity中实现TimePickerDialog.OnTimeSetListener,而是将其提供给构造函数中的片段。这样每个实例都可以做一些不同的事情。

所以你会像:

一样使用它
  frag1 = new TimePickerFragment(new TimePickerDialog.OnTimeSetListener() { /* Your implementation*/ });

答案 2 :(得分:0)

活动,其中editText的onClick()出现一个带有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>