1

我有一个 timePicker 对话框,可以从不同的按钮调用。如何传递调用对话框的 ID?

这是相关的代码:

    //Time picker
    private int pHour;
    private int pMinute;
    static final int TIME_DIALOG_ID = 0;

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

        /** Get the current time */
        final Calendar cal = Calendar.getInstance();
        pHour = cal.get(Calendar.HOUR_OF_DAY);
        pMinute = cal.get(Calendar.MINUTE);
}

按钮的点击事件:

public void onClick(View v) {

 // Here I should pass the v.getId() to the dialog
 showDialog(TIME_DIALOG_ID);
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case TIME_DIALOG_ID:
        return new TimePickerDialog(this,
                mTimeSetListener, pHour, pMinute, false);
    }
    return null;
}

/** Callback received when the user "picks" a time in the dialog */
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            pHour = hourOfDay;
            pMinute = minute;
            //Here I should know from which v.getId() the dialog was called
        }
    };

谢谢!

4

1 回答 1

1

您将不得不为您想要做的事情编写自己的选择器:

假设您必须为所有按钮调用相同的选择器,我建议您使用,switch声明Button

 public void onClick(View v) {

  switch(v.getId()){

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

  case R.id.Button2: 
       showDialog(TIME_DIALOG_ID);
       break;
  }
}

Dialog如果您想Dialog弹出不同的ID,您可以使用不同的 ID。

于 2012-05-20T13:24:47.413 回答