我正在开发 Android 自学 Sunshine 应用程序,但在操作栏中获取额外的菜单条目时遇到问题。
我发现的最可能的原因是我的框架类的 OnCreate
方法没有被调用,因此菜单没有被膨胀。
这是我的 MainActivity 代码:
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
方法的日志记录。
有什么想法吗?
最佳答案
这不是Fragment确切继承的onCreate方法
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate()");
}
它应该是onCreate
而不是OnCreate
关于java - OnCreate方法没有被调用(Sunshine应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41282409/