Derek Seabrooke
Derek Seabrooke

Reputation: 123

Timepicker without cancel button?

How do you create an Android timepicker without a cancel button? I would had expected setCancelable(false) would do this, but does not get rid of the button, it only seems to prevent cancellations from clicking outside of the window or back button.

Upvotes: 3

Views: 2659

Answers (2)

Surabhi Singh
Surabhi Singh

Reputation: 803

If you don't want cancel button for time picker, better to use time picker in your xml file like:

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

and your activity should be like :

import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {
   private TimePicker timePicker1;
   private TextView time;
   private Calendar calendar;
   private String format = "";

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

      timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
      time = (TextView) findViewById(R.id.textView1);
      calendar = Calendar.getInstance();

      int hour = calendar.get(Calendar.HOUR_OF_DAY);
      int min = calendar.get(Calendar.MINUTE);
      showTime(hour, min);
  }

  public void setTime(View view) {
     int hour = timePicker1.getCurrentHour();
     int min = timePicker1.getCurrentMinute();
     showTime(hour, min);
  }

  public void showTime(int hour, int min) {
     if (hour == 0) {
        hour += 12;
        format = "AM";
     }
     else if (hour == 12) {
        format = "PM";
     } else if (hour > 12) {
        hour -= 12;
        format = "PM";
     } else {
        format = "AM";
     }
     time.setText(new StringBuilder().append(hour).append(" :     ").append(min)
  .append(" ").append(format));
  }


 }

this is for reference, hope this will help you .. Thanks :)

Upvotes: 0

Mike
Mike

Reputation: 4570

If you'd like to use the TimePickerDialog, it is pretty simple. You just simply need to detect when the dialog is shown, look up the NEGATIVE button since that serves the "Cancel" one and set it's visibility to GONE..like this:

final TimePickerDialog timePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
         // Do something with the time
    }
}, 12, 25, true); // 12 is the hour and 25 is minutes..please change this

timePicker.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {
        // This is hiding the "Cancel" button:
        timePicker.getButton(Dialog.BUTTON_NEGATIVE).setVisibility(View.GONE);
    }
});
timePicker.show();

Upvotes: 3

Related Questions