Android中Fragment是依附于实际的FragmentActivity的,所以Fragment无法像Activity那样调用finish()方法销毁自己。
但是,很多场合下,我们又需要把自己关闭掉。
同时,我们知道触摸返回键是可以关掉当前Fragment。
那就好办了:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.scenes_main,null);mToolbar = (Toolbar)view.findViewById(R.id.toolbar);
mToolbar.setTitle("");( (AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setBackgroundResource(R.color.navigation);
TextView tv = (TextView) mToolbar.findViewById(R.id.title_sub);
tv.setText(R.string.sleep_scene);
int white = getResources().getColor(R.color.white_80);tv.setTextColor(white);
//返回按键
Drawable upArrow = getContext().getDrawable(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material);
upArrow.setColorFilter(white, PorterDuff.Mode.SRC_ATOP);
( (AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(upArrow);//关键下面两句话,设置了回退按钮,及点击事件的效果
( (AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {getActivity().onBackPressed();//销毁自己
}。
});init(view);
return view;
}
---------------------
作者:梦想之家xiao_chen
来源:CSDN
原文:https://blog.csdn.net/qq_32014215/article/details/64438531
版权声明:本文为博主原创文章,转载请附上博文链接!