1

我是 android 新手,我承认我不完全理解适用于 Android 的上下文是什么。我明白一点,但不完全。我正在尝试修改 Android Datepicker,以便只有日期和月份在 DatePickerDialog 中。我问了stackoverflow,并以三个代码块的形式给出了一个答案。代码如下。我的问题是我在 mDialog = new CustomDPDialog(getContext(), this,... 处遇到一个错误,错误在getContext(). 它说这getContext()是未定义的onClickListener。那么,看看下面的代码,解决方法是getContext()什么?创建一个getContext()方法实际上会更糟地破坏代码。并使用上下文, null 代替getContext(), this,擦除错误,但它不应该是 null,它应该是this.

static final int ID_DATEPICKER = 0;
private int myYear, myMonth, myDay;
TextView dateDisplay;
Dialog mDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    dateDisplay = (TextView)findViewById(R.id.dateDisplay);

    Button datePickerButton = (Button)findViewById(R.id.datepickerbutton);
    datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
    }
private Button.OnClickListener datePickerButtonOnClickListener
= new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        final Calendar c = Calendar.getInstance(); 
        mDialog = new CustomDPDialog(getContext(), this, 
        c.get(Calendar.YEAR), c.get(Calendar.MONTH), 
        c.get(Calendar.DAY_OF_MONTH)); 
        mDialog.show(); 
        DatePicker dp = findDatePicker((ViewGroup) mDialog.getWindow().getDecorView()); 
        if (dp != null) { 
        ((ViewGroup) dp.getChildAt(0)).getChildAt(0).setVisibility(View.GONE);
        }
    }

    class CustomDPDialog extends DatePickerDialog {
        public CustomDPDialog(Context context, 
                OnDateSetListener callBack, int myYear, int myMonth, 
                int myDay) {
                super(context, callBack, myYear, myMonth, myDay);
                }
        @Override 
        public void onDateChanged(DatePicker view, int year, int month, int day) {
            super.onDateChanged(view, year, month, day);
            mDialog.setTitle((month + 1) + "-" + day + "-");
        }

    }

    private DatePicker findDatePicker(ViewGroup group) {
        if (group != null) {
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                View child = group.getChildAt(i);
                if (child instanceof DatePicker) {
                    return (DatePicker) child;
                } else if (child instanceof ViewGroup) {
                    DatePicker result = findDatePicker((ViewGroup) child);
                    if (result != null)
                        return result;
                }
            }
        }
        return null;
    }
};
}
4

3 回答 3

2

尝试

v.getContext()

或者

getApplicationContext()

我推荐第一个,因为 getApplicationContext() 有时会导致问题

于 2012-05-04T21:58:51.547 回答
0

ActivityName.this应该管用

于 2012-05-04T22:16:56.810 回答
0

getActivity()应该为您解决问题。

于 2012-05-04T22:13:13.380 回答