我有一个 fragment ,其中启用了操作栏后退按钮。
代码 :
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
setHasOptionsMenu(true);
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setCustomView(R.layout.custom_action_bar);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.fragment_layout, container, false);
return view;
}
上述代码中
actionBar.setDisplayHomeAsUpEnabled(true);
启用操作栏中的后退按钮,但我们如何检测对它的点击?我查看了许多示例并尝试了以下但仍然无法正常工作:
在 fragment 中:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getActivity(), "Back", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
fragment 中显示的后退按钮也是黑色的,我需要白色或自定义颜色的按钮,我该如何更改?
最佳答案
迟到总比没有好,请试试这个>
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.fragment_layout, container, false);
//set setHasOptionsMenu on true here on CreateView method
setHasOptionsMenu(true);
return view;
}
并实现
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == android.R.id.home) {
if (getActivity() != null) {
getActivity().onBackPressed();
}
return true;
};
return super.onOptionsItemSelected(item);
}
关于android - 操作栏检测 fragment 中的后退按钮单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29138629/