Android Studio:使用单个textView和单个TimePickerDialog作为嵌套本地类 点击TimePickerDialog并且onTimeSet运行TWICE。
点击一次,它应该只运行一次。 (即" toast"不应显示PartyTime Set:0然后立即PartyTime设置:1)
为什么两次?...我怎样才能让它只运行一次?
public class MainActivity extends ActionBarActivity {
int n_Count;
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Calendar calPartyTime = Calendar.getInstance();
int ct_hourParty = calPartyTime.get(Calendar.HOUR_OF_DAY);
int ct_minuteParty = calPartyTime.get(Calendar.MINUTE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimePickerDialog timePickerParty = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
calPartyTime.set(Calendar.HOUR_OF_DAY, selectedHour);
calPartyTime.set(Calendar.MINUTE, selectedMinute);
String date = dateFormat.format(calPartyTime.getTime());
TextView tv_PartyTime = (TextView) findViewById((R.id.partyTimeTextView));
tv_PartyTime.setText(date);
Toast.makeText(getApplicationContext(), "Party Time Set!:" + n_Count , Toast.LENGTH_SHORT).show();
n_Count++;
}
}, ct_hourParty, ct_minuteParty, true);
timePickerParty.setTitle("Set Party UTC (HH:MM)");
timePickerParty.show();
}
}
答案 0 :(得分:3)
你可以添加一些我曾经使用的逻辑(使用布尔变量并检查其值 -
public static class DatePickerFragment extends DialogFragment implements OnDateSetListener {
boolean mFirst = true;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
if (mFirst) {
mFirst = false;
// Do something with the date chosen by the user
currentYear = year;
currentMonth = month;
currentDay = day;
DialogFragment newFragment2 = new TimePickerFragment();
newFragment2.show(getFragmentManager(), "timePicker");
}
}
}
希望这会有所帮助:)