本文主要是介绍ToolBar封装策略,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
作者:Ming_
链接:https://juejin.im/post/5ac1a251f265da2397070463
效果:
策略一: 使用原生toolbar进行封装
流程:
* 1所有的类都继承此AppToolBarActivity.* 2打气筒加载一个布局到根布局(即layout_toolbar),此布局包含ToolBar+Framelayout.* 3getContentView()为抽象方法,返回一个View 将此View add到framelayout中.* 4做一些ToolBar的初始化操作.* 5使用
@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);View view = LayoutInflater.from(this).inflate(R.layout.layout_toolbar, (ViewGroup) getWindow().getDecorView().getRootView(), false);mContent_frame = view.findViewById(R.id.content_frame);if(getContentView() != null){mContent_frame.addView(getContentView());}setContentView(view);ButterKnife.bind(this);steepTitle();setSupportActionBar(mToolbar);getSupportActionBar().setTitle("");getSupportActionBar().setDisplayHomeAsUpEnabled(true);getSupportActionBar().setDisplayShowHomeEnabled(true);setTitle(getTitle());initWidget();initData();}
- 处理ToolBar的返回事件:
//style.xml中<item name="android:homeAsUpIndicator">@mipmap/back_white</item>//AppToolBarActivity中@Overridepublic boolean onOptionsItemSelected(MenuItem item) {if(item.getItemId() == android.R.id.home){onBackPressed();}return super.onOptionsItemSelected(item);}
- 处理中间Title 重写setTitle()
//bar 中间标题@Overridepublic void setTitle(CharSequence title) {mToolbar_tv_title.setText(title);mRadioGroup.setVisibility(View.GONE);}
- 处理右侧可能是文字或图片按钮 中间可能是多按钮
//bar右侧是文字protected void setRightTextButtonEnable(@StringRes int rid, View.OnClickListener onClickListener) {mTv_title_right.setText(rid);mTv_title_right.setOnClickListener(onClickListener);mTv_title_right.setVisibility(View.VISIBLE);}//bar右侧是图标protected void setRightImageButtonEnable(@DrawableRes int rid, View.OnClickListener onClickListener) {mIv_title_right.setImageResource(rid);mIv_title_right.setOnClickListener(onClickListener);mIv_title_right.setVisibility(View.VISIBLE);mTv_title_right.setVisibility(View.GONE);}//bar中间是多按钮protected void setCenterRadioGroupEnable(String btnLefttext,String btnRighttext, RadioGroup.OnCheckedChangeListener onClickListener) {mRadioBtnLeft.setText(btnLefttext);mRadioBtnRight.setText(btnRighttext);mRadioGroup.setOnCheckedChangeListener(onClickListener);mRadioGroup.setVisibility(View.VISIBLE);mToolbar_tv_title.setVisibility(View.GONE);}
- 处理所谓的沉浸式
//加载沉浸式状态栏public void steepTitle() {if (Build.VERSION.SDK_INT >= 21) {getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);//注意要清除 FLAG_TRANSLUCENT_STATUS flaggetWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);getWindow().setStatusBarColor(getResources().getColor(R.color.maincolor));}}
- 最后使用超简单:
@Overrideprotected View getContentView() {return initRId(R.layout.activity_main);}@Overrideprotected void initWidget() {setBackEnable(false);setTitle("主页");}
github地址传送门
公众号 分享Java,Android知识
这篇关于ToolBar封装策略的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!