我有一个片段,其中启用了操作栏后退按钮。
代码:
@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);
中启用操作栏中的后退按钮,但我们如何检测其上的点击?
我已经研究过很多例子并试过以下但仍然没有工作:
在片段中:
@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);
}
片段中显示的后退按钮是黑色,我需要白色或自定义颜色,我怎么能改变呢?
答案 0 :(得分:3)
迟到总比没有好,请试试这个>
@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);
}
答案 1 :(得分:2)
我遇到了同样的问题,但后来我把这个代码放在了活动中,后面的按钮在片段里面工作了:
for
答案 2 :(得分:-1)
View cView = getLayoutInflater().inflate(R.layout.header, null);
cView.findViewById(R.id.btn_id).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do stuff here.
}
});
actionBar.setCustomView(cView);