简体   繁体   中英

Using a TimePicker, DatePicker, and an AlertDialog in the same class/activity

I've got 3 buttons contained within one Activity. The first button is used to launch a custom AlertDialog with an EditText. The second button needs to open a DatePicker. The third button needs to open a TimePicker. I've got the first button working just fine, and I have the code I need for the second button, but the only way I could get that code to work was to create a different activity.

What do I need to do to implement all three of these things in the same Activity? Is it even possible, I'm pretty new to all of this stuff, so any basic to advanced suggestions would be great!!

Here's the code for the activity with the three buttons, all of which are declared in the corresponding XML file. This is the code I currently have, which means only the code for the AlertDialog is working correctly:

package com.example.test_project;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;


public class NewWorkout extends Activity  {

@Override
protected void onCreate(Bundle onSaveInstanceState) {
    super.onCreate(onSaveInstanceState);
    setContentView(R.layout.activity_new_workout);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.new_workout, menu);
    return true;
}
public void timeOfWorkout(View view){
    Intent intent = new Intent(this, TimePickerFragment.class);
    startActivity(intent);
}


    int mYear;
    int mMonth;
    int mDay;

    TextView mDateDisplay;


    final int DATE_DIALOG_ID = 0;

    public void onCreate1(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_workout);

        mDateDisplay = (TextView) findViewById(R.id.timeOfWorkoutTextView);        
        Button button = (Button) findViewById(R.id.dateOfWorkoutButton);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 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);

                // display the current date
                updateDisplay();
            }
            });
                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() {
     this.mDateDisplay.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));



}

public void nameOfWorkout(View view){
    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Enter a Name for This Workout");

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    alert.setView(input);

    alert.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);
      }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
      }
    });

    alert.show();

}

}

You should be implementing the DatePicker and TimePicker using a Dialog Fragment.

Here are some samples from this documentation:

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

You could use a time picker off of you button like this:

in your xml:

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:text="@string/pick_time" 
    android:onClick="showTimePickerDialog" />

then in your activity:

public void showTimePickerDialog(View v) {
    FragmentManager manager = getSupportFragmentManager();
    DialogFragment timePickerFragment = new TimePickerFragment();
    timePickerFragment.show(manager, "timePicker");
}

try this code for date and time picker dialog

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

}


private void calendarDataInit() {

    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);
    mHour = c.get(Calendar.HOUR_OF_DAY);
    mMinute = c.get(Calendar.MINUTE);

}


private void initViews() {

    imgViewDatePicker = (ImageView) findViewById(R.id.imgViewDatePicker);
    imgViewTimePicker = (ImageView) findViewById(R.id.imgViewTimePicker);
    imgViewDatePicker.setOnClickListener(this);
    imgViewTimePicker.setOnClickListener(this);     

@Override
public void onClick(View v) {

    switch (v.getId()) {
    case R.id.imgViewDatePicker:
        showDialog(DATE_DIALOG_ID);
        break;

    case R.id.imgViewTimePicker:
        showDialog(TIME_DIALOG_ID);
        break;




private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, 
            int monthOfYear, int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        updateDate();
    }

    private void updateDate() {
        adapter.resetData();
        StringBuilder dateEvent = new StringBuilder().append(mYear).append("-").append(padMonth(mMonth + 1))
                .append("-")
                .append(mDay);
        editTxtDtae.setText(dateEvent);
        editTxtDtae.requestFocus();


    }
};

private static String padMonth(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}


// Timepicker dialog generation
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        mHour = hourOfDay;
        mMinute = minute;
        updatetime();
    }

    private void updatetime() {

        adapter.resetData();

        String am_pm;

        if(mHour > 12) {
            am_pm = "PM";
            mHour = mHour - 12;
        } else {
            am_pm = "AM";
        } 

        timeEvent = new StringBuilder().append(mHour)
                .append(":").append(mMinute).append(am_pm);
        editTxtTime.setText(timeEvent);
    }


};
private static String pad(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}

@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,
                mTimeSetListener, mHour, mMinute, false);

    }
    return null;
}
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM