您的位置:首页 > 其它

ToolBar的封装

2016-03-23 12:26 477 查看
1.ToolBarHelper.java

这个类的功能是:先创建一个 ViewGroup 来作为视图的父 View,把用户定义的 View,和 toolBar 依次 Add 到 ViewGroup 中;

public class ToolBarHelper {
private Context mContext;
private FrameLayout mContentView;
/*用户定义的view*/
private View mUserView;
/*toolbar*/ private Toolbar mToolBar;
/*视图构造器*/ private LayoutInflater mInflater; /*
* 两个属性
* 1、toolbar是否悬浮在窗口之上
* 2、toolbar的高度获取
* */
private static int[] ATTRS = {
R.attr.windowActionBarOverlay,
R.attr.actionBarSize
};
public ToolBarHelper(Context context, int layoutId) {
this.mContext = context;
mInflater = LayoutInflater.from(mContext);
/*初始化整个内容*/
initContentView();
/*初始化用户定义的布局*/
initUserView(layoutId);
/*初始化toolbar*/
initToolBar();
}
private void initContentView() { /*直接创建一个帧布局,作为视图容器的父容器*/
mContentView = new FrameLayout(mContext);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
mContentView.setLayoutParams(params);
}
private void initToolBar() { /*通过inflater获取toolbar的布局文件*/
View toolbar = mInflater.inflate(R.layout.toolbar, mContentView);
mToolBar = (Toolbar) toolbar.findViewById(R.id.id_tool_bar);
}
private void initUserView(int id) {
mUserView = mInflater.inflate(id, null);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
TypedArray typedArray = mContext.getTheme().obtainStyledAttributes(ATTRS);
/*获取主题中定义的悬浮标志*/
boolean overly = typedArray.getBoolean(0, false);
/*获取主题中定义的toolbar的高度*/
int toolBarSize = (int) typedArray.getDimension(1, (int) mContext.getResources().getDimension(R.dimen.abc_action_bar_default_height_material));
typedArray.recycle(); /*如果是悬浮状态,则不需要设置间距*/
params.topMargin = overly ? 0 : toolBarSize;
mContentView.addView(mUserView, params);
}
public FrameLayout getContentView() {
return mContentView;
}
public Toolbar getToolBar() {
return mToolBar;
}
}


2.ToolBarActivity.java

public abstract class ToolBarActivity extends AppCompatActivity {
private ToolBarHelper mToolBarHelper;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void setContentView(int layoutResID) {
mToolBarHelper = new ToolBarHelper(this, layoutResID);
toolbar = mToolBarHelper.getToolBar();
setContentView(mToolBarHelper.getContentView()); /*把 toolbar 设置到Activity 中*/
setSupportActionBar(toolbar); /*自定义的一些操作*/
onCreateCustomToolBar(toolbar);
}
public void onCreateCustomToolBar(Toolbar toolbar) {
toolbar.setContentInsetsRelative(0, 0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: