2 回答
TA贡献1806条经验 获得超8个赞
显然#getActivity() 在附加片段之前为空。
您应该尝试将赋值代码放在#onCreateDialog()方法中:
TextView moon_ra;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
moon_ra = (TextView)getActivity().findViewById(R.id.moon_ra);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
TA贡献1859条经验 获得超6个赞
您可以使用从到onActivityResult()传递数据,如下所示。SelectDateFragmentMoonFragment
SelectDateFragment如下所示在您的内部调用MoonFragment。
moon_date.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.setTargetFragment(this, 111); // add this line
newFragment.show(getFragmentManager(), "DatePicker");
}
});
发送数据从SelectDateFragment到MoonFragment新日期设置时
public void populateSetDate(int year, int month, int day) {
String newDate = month+"/"+day+"/"+year;
Intent intent = new Intent();
intent.putStringExtra("date", newDate);
getTargetFragment().onActivityResult(getTargetRequestCode(), 111, intent);
}
要接收数据,请使用onActivityResult您的MoonFragment
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 111) {
String newDate = data.getStringExtra("date");
// here you can update your textview
moon_ra.setText(newDate); // make sure your moon_ra textview is decleared globally
}
}
添加回答
举报