1

我现在只开发 Android 两个星期,并且已经对我遇到的这个问题进行了很多谷歌搜索,但似乎无法解决任何问题。

我有一个助手类,它有一种设置DatePicker限制等的方法。

public class AlarmHelper extends Activity {

    public void setupDatePicker(){
        long maxTime = 52560000;
        final Calendar cal = Calendar.getInstance();
        DatePicker dp = (DatePicker)findViewById(R.id.datePicker);
        dp.setMinDate(cal.getTimeInMillis() - 1000);
        dp.setMaxDate(cal.getTimeInMillis() + maxTime);
    }

}

然后我尝试像这样setupDatePicker()从方法MainActivity中调用。onCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    AlarmHelper helper = new AlarmHelper();
    helper.setupDatePicker();

    setContentView(R.layout.activity_main);
}

当我运行应用程序时,我得到一个NullPointerException. 我相信它与上下文有关,但我不知道如何在我的助手类中实现它。

任何帮助将不胜感激。

4

2 回答 2

2

目前您正在尝试findViewById在设置活动布局之前将您的活动onCreate代码更改为:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

       // your code here...
    setContentView(R.layout.activity_main);   //<< set layout for Activity here

    AlarmHelper helper = new AlarmHelper(MainActivity.this);
    helper.setupDatePicker();


}

并且在您的 AlarmHelper 中,如果它不是 Activity ,则无需扩展 Activity 类。更改您的AlarmHelper类,因为要从其他非 Activity 类访问 UI 元素,您需要传递活动上下文:

public class AlarmHelper  {

Activity activity;

public AlarmHelper(Activity activity){
  this.activity=activity;
}

    public void setupDatePicker(){
        long maxTime = 52560000;
        final Calendar cal = Calendar.getInstance();
        DatePicker dp = (DatePicker)activity.findViewById(R.id.datePicker);
        dp.setMinDate(cal.getTimeInMillis() - 1000);
        dp.setMaxDate(cal.getTimeInMillis() + maxTime);
    }

}
于 2013-01-16T17:36:58.293 回答
0

解决方案:将 setContentView() 移到 setupDatePicker() 之前

 super.onCreate(savedInstanceState);
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,    WindowManager.LayoutParams.FLAG_FULLSCREEN);
 setContentView(R.layout.activity_main);

 AlarmHelper helper = new AlarmHelper();
 helper.setupDatePicker();

反正在activity里面创建一个activity是很可怕的!

于 2013-01-16T17:39:00.327 回答