就这么简单,当我按下后退按钮时没有任何反应。 这是运行的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tm_activity_inicio_resumen, container, false);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_left2);
return view;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getActivity().getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
这个实现有问题吗?
答案 0 :(得分:1)
更改为此代码。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
答案 1 :(得分:0)
如果你想要片段上的动作栏菜单那么
覆盖片段上的onCreateOptionsMenu。并清除活动菜单
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
//if you dont have options skip inflate
inflater.inflate(R.menu.menu_second, menu);
}
和
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Toast.makeText(getActivity().getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}