您好我是Android和Java的新手,我正在编写一个Date Picker Fragment类,它扩展DialogFragment
并实现DatePickerDialog.OnDateSetListener
,因为我必须声明方法public void onDateSet(DatePicker view, int year, int month, int day)
,我在public
String
变量中设置了我的新约会。
我可以在主活动中使用此public String
变量来显示TextView
中的值吗?如果是,如何?
我的主要活动代码是:
public class TARForm extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
EditText departuredate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tarform);
departuredate = (EditText) findViewById(R.id.departure_date);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
}
DatePickerFragment
代码为:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
int selectyear, selectmonth, selectday;
public String date;
@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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
selectday = day;
selectmonth = month+1;
selectyear = year;
date = selectday + "-" + selectmonth + "-" + selectyear;
}
}
如果您可以引导这些信息,我如何才能获得MainActivity离职人员的“约会”?感谢。
答案 0 :(得分:0)
//In your actiivty
String date=null;
public void setDate(String date){
this.date=date;
//set this date in your text View
}
//In your fragment
Context context;
@Override
public void onAttach(Context context){
this.context=context;
}
public void onDateSet(DatePicker view, int year, int month, int day){
String date=//get Date over here
((TARForm)context).setDate(date)
}
答案 1 :(得分:0)
您可以在 onDateSet()方法
中的片段中尝试以下代码public void onDateSet(DatePicker view, int year, int month, int day) {
selectday = day;
selectmonth = month+1;
selectyear = year;
date = selectday + "-" + selectmonth + "-" + selectyear;
if(getActivity() instanceOf TARForm){
((TARForm)getActivity()).departuredate.setText(date);
}
}
如果您的活动和片段位于不同的文件夹中,并在您的 TARForm 活动中生成public EditText departuredate;