我正在编写一个简单的应用程序,它打开一个时间选择器对话框,要求输入,根据系统时间检查它,并告诉你它是否正确。但是,我需要获取显示它是真还是假的 TextView,并在 TimePickerFragment 中更改它,它是一个 DialogFragment。我应该怎么办?
TimePickerFragment.java
package com.example.timechecker;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
int hour;
int minutes;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, 12, 00,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//Grab the Text View from the Main Activity
// MainActivity m = new MainActivity();
// m.grabText text = new m.grabText();
//Check if given Picker value is == to the system time, display whether or not it is so
if (hourOfDay == hour && minutes == minute) {
text.setText("You are correct!");
} else {
text.setText("You are incorrect!");
}
}
}
MainActivity.java
package com.example.timechecker;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Creates the dialog with the Time Picker
public void checkTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
//Class to grab the Text View for the Dialog Fragment
public class grabText {
TextView text = (TextView) findViewById(R.id.whatTime);
//Uses a method to set the Text View text
public void setText(String string) {
text.setText(string);
}
}
}