您的应用程序崩溃可能是因为这个
TextView tvDate1 = (TextView) getView().findViewByiD(R.id.tvDate);
我猜你的选择器在不同的文件中,你正在尝试初始化 textview。findViewById
是活动类的方法
使用接口
http://developer.android.com/guide/components/fragments.html
检查与活动沟通下的主题
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
TheListener listener;
public interface TheListener{
public void returnDate(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);
listener = (TheListener) getActivity();
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
if (listener != null)
{
listener.returnDate(formattedDate);
}
}
}
然后在 MainActivity 中实现接口并将日期设置为 textview
public class MainActivity extends Activity implements DatePickerFragment.TheListener{
Button b;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b= (Button) findViewById(R.id.button1);
tv= (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
});
}
@Override
public void returnDate(String date) {
// TODO Auto-generated method stub
tv.setText(date);
}
}