Toolbar简单封装
1、常规方法
对Toolbar进行封装,为后续使用做铺垫,作者认为常见的对Toolbar封装的有2中方法。
第一种在BaseActivity中封装,这种封装不足之处在于BaseActivity会比较复杂,耦合性高,不利于后期维护,BaseActivity一般封装语言切换等(个人见解可能有误)。
第二种封装Toolbar的同时,还需要在布局文件中使用<include>导入ToolBar布局,或者直接写ToolBar布局,不利于维护,例如:Activity中删除Toolbar的同时,还要删除<include>导入的ToolBar布局(个人见解可能有误)。
2、本文方法
2.1 Toolbal的布局文件"layout_toolbar.xml"
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorWhite"
android:elevation="4dp">
<ImageView
android:id="@+id/tb_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_back"
android:clickable="true"/>
<ImageView
android:id="@+id/tb_ver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_vertical"/>
<TextView
android:id="@+id/tb_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="ECG"/>
</android.support.v7.widget.Toolbar>
2.2 style修改
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
2.3 color修改
<!-- Custom the color -->
<color name="colorWhite">#FFFFFF</color>
2.4 封装Toolbar类代码
public class SettingToolBar {
/**
* Set the toolbar
* @param activity It represents current using activity
* @param toolbarTitle It represents title of toolbar
*/
public SettingToolBar(final Activity activity, String toolbarTitle){
// Setting the animation of toolbar
final ScaleAnimation sa = new ScaleAnimation(1,2,1,1,
Animation.RELATIVE_TO_PARENT,0.5f,Animation.RELATIVE_TO_PARENT,0.5f);
sa.setDuration(500);
// Get the root layout
ViewGroup parentView = (ViewGroup)activity.findViewById(android.R.id.content);
// Add the toolbar into the layout
LayoutInflater inflater = LayoutInflater.from(activity);
Toolbar toolbar = (Toolbar)inflater.inflate(R.layout.layout_toolbar, parentView, false);
parentView.addView(toolbar);
// Set the backImage
ImageView tbBack = (ImageView) toolbar.findViewById(R.id.tb_back);
// Add the event
tbBack.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
view.startAnimation(sa);
activity.finish();
}
});
// Set the title of toolbar
((TextView)toolbar.findViewById(R.id.tb_title)).setText(toolbarTitle+"");
}
}
2.5 Activity代码
public class MainActivity extends BaseAppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new SettingToolBar(this, "Toolbar");
}
}