永久设置日期拾取器对话框标题

2022-09-02 23:47:28

当我尝试永久设置DatePickerDialog标题时,我遇到了一个问题。

DatePickerFragment.java

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @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);

    // Create a new instance of DatePickerDialog and return it
    DatePickerDialog dpd = new DatePickerDialog(getActivity(), this, year, month, day);
    dpd.setTitle("set date");
    return dpd;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
    // Do something with the date chosen by the user
    }
}

主要活动.java

public class MainActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getSupportFragmentManager(), "datePicker");

            }
        });
    }
}

当我单击按钮DatePickerDialog显示并且对话框标题是“设置日期”时,但是当我更改日期时,标题包含所选日期而不是“设置日期”。如何永久设置此对话框标题?

已在 API 8-10 上进行测试。

提前谢谢你,对不起我的英语。帕特里克


答案 1

如何扩展和添加一种方法来存储永久标题,该标题将在日期更改时强制使用?DatePickerDialogsetPermanentTitle

public class MyDatePickerDialog extends DatePickerDialog {

    private CharSequence title;

    public MyDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public void setPermanentTitle(CharSequence title) {
        this.title = title;
        setTitle(title);
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int month, int day) {
        super.onDateChanged(view, year, month, day);
        setTitle(title);
    }
}

然后使用新方法:setPermanentTitle

    MyDatePickerDialog dpd = new MyDatePickerDialog(this, null, 2012, 10, 10);
    dpd.setPermanentTitle("set date");

答案 2

Extend DatePickerDialog 并覆盖 setTitle() 方法。

public class MyDatePickerDialog extends DatePickerDialog {

   public MyDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
       super(context, callBack, year, monthOfYear, dayOfMonth);
   }

   public void setTitle(CharSequence title) {
       super.setTitle(*<whatever title you want>*);
   }
}

推荐