您的代码对我有用,显示方法没有错误。检查是否导入正确的库(例如 android.support.v4.app.* 如果您使用支持库)。
编辑 - 完整的源代码:
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java
package com.viduka.stackoverflow;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, new AFragment());
ft.commit();
}
}
AFragment.java - 从中调用 DatePickerFragment
package com.viduka.stackoverflow;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.EditText;
public class AFragment extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDatePickerDialog(new EditText(getActivity()));
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment(new EditText(getActivity()));
newFragment.show(getFragmentManager(), "datePicker");
}
}
DatePickerFragment.java
package com.viduka.stackoverflow;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.EditText;
@SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
public EditText activity_edittext;
public DatePickerFragment(EditText edit_text) {
activity_edittext = edit_text;
}
@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);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
activity_edittext.setText(String.valueOf(day) + "/"
+ String.valueOf(month + 1) + "/" + String.valueOf(year));
}
}