有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

未调用java OnCreate方法(Sunshine应用程序)

我正在开发安卓自学阳光应用程序,但在操作栏中获取额外菜单项时遇到了问题

我发现的最可能的原因是没有调用框架类的OnCreate方法,因此菜单没有膨胀

这是我的主要活动代码:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("MainActivity","OnCreate Started 1");
    if (savedInstanceState == null) {
        Log.d("MainActivity","OnCreate Started 2");
        ForecastFragment MyFragment = new ForecastFragment();
        if (MyFragment == null){
            Log.d("MainActivity","OnCreate Started 3");
        }
        else{
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, MyFragment)
                .commit();}
    }
}

下面是我的ForecastFragment类的代码:

public class ForecastFragment extends Fragment {

public ForecastFragment() {
}

//@Override
protected void OnCreate(Bundle savedInstanceState){
    Log.d("Forecastfragment","OnCreate Started");
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Inflate the menu; this adds items to the action bar if it is present.

    inflater.inflate(R.menu.forecastfragment, menu);

}

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_refresh) {
        FetchWeatherTask WeatherTask = new FetchWeatherTask();
        WeatherTask.execute();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

当我运行应用程序时,我没有看到正在调用ForecastFragment类的OnCreate方法的日志记录

有什么想法吗


共 (1) 个答案

  1. # 1 楼答案

    这不是片段的继承onCreate方法

     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.i(TAG, "onCreate()");
        }
    

    它应该是onCreate而不是OnCreate