在我的应用程序中,我使用NoActionBar样式,并且要将 Action 栏添加到 fragment 之一。
在 Activity 中,我可以这样:
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
如何分段?
我是这样尝试的:
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toolbar actionBar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(actionBar);
return inflater.inflate(R.layout.fragment_training, container, false);
}
但这是行不通的。
UPD
我认为这条线的问题是:
Toolbar actionBar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(actionBar);
最佳答案
旧问题)),应为:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
//((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//return inflater.inflate(R.layout.fragment_training, container, false);
View v = inflater.inflate(r.layout.fragment_training, container, false);
Toolbar toolbar = (Toolbar) v.findviewbyid(r.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
return v;
}