今天下午没事,刚刚完成了电商的规格功能,现在没事就来把我封装的BaseActivity给贴出来,我们在开始学习的时候,老师或者网上对初学者得到控件ID都是findViewbyid(R.id.xxx);这样的去得到控件ID,要嘛就是用注解的方式得到,我觉得这样很麻烦,反而会增加代码量,这些都是可规避的。先看看注解的用法
注解
@BindView(R.id.xxx)//这儿的ID是布局中的ID
Button btnstart;//这儿也可以跟布局文件中的ID相同也可以不同
但是这样我觉得多了@BindView(R.id.xxx)这个注解会造成很多不必要的代码,但是他跟findViewbyid差不多,在Activity或者fragment中可以不用跟自定义ID一模一样,他的优点是这样,(其他的我还没有去仔细了解),有了解的童鞋自己去看一下。好了,废话不多说了我们先上代码吧!
自定义BaseActivity
package com.base;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import com.activity.R;
import com.util.DensityUtil;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/***
* BaseActivity封装,不用findViewbyid得到控件ID,沉侵式状态栏自定义,侧滑返回
* setStatusBarColor(R.color.colorAccent);//默认颜色
*/
public abstract class BaseActivity extends FragmentActivity implements View.OnClickListener {
private View statusBar;
private LinearLayout container;
/**
* 是否开启 右划关闭activity 手势,默认开启
*/
private boolean isGestureOpen = true;
@SuppressLint("InlinedApi")
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
statusBar = new View(this);
ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
getStatusBarHeight());
//添加状态栏VIew
statusBar.setLayoutParams(param);
setStatusBarColor(R.color.colorAccent);//默认颜色
container = new ViewContainer(getApplicationContext());
container.setOrientation(LinearLayout.VERTICAL);
container.addView(statusBar);
}
}
public abstract void onClick(View view);
/**
* 设置状态栏颜色,
*
* @param color 颜色资源id, 如 R.color.orange
* 0 黑色
*/
protected void setStatusBarColor(int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (color == 0) {
statusBar.setBackgroundColor(Color.BLACK);//默认黑色
} else {
statusBar.setBackgroundColor(getResources().getColor(color));
}
}
}
/***
* 统一设置ID
*
* @param layoutResID
*/
@Override
public void setContentView(@LayoutRes int layoutResID) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
LayoutInflater.from(this).inflate(layoutResID, container, true);
setContentView(container);
} else {
super.setContentView(layoutResID);
}
smartInject();
}
/**
* 获取状态栏高度
*
* @return
*/
protected int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* 设置是否允许屏幕左侧 快速 右划关闭activity,默认允许
*
* @param b
*/
protected void isGestureSensitive(boolean b) {
isGestureOpen = b;
}
private void smartInject() {
try {
Class extends Activity> clz = getClass();
while (clz != BaseActivity.class) {
Field[] fs = clz.getDeclaredFields();
Resources res = getResources();
String packageName = getPackageName();
for (Field field : fs) {
if (!View.class.isAssignableFrom(field.getType())) {
continue;
}
int viewId = res.getIdentifier(field.getName(), "id", packageName);
if (viewId == 0)
continue;
field.setAccessible(true);
try {
View v = findViewById(viewId);
field.set(this, v);
Class> c = field.getType();
Method m = c.getMethod("setOnClickListener", android.view.View.OnClickListener.class);
m.invoke(v, this);
} catch (Throwable e) {
}
field.setAccessible(false);
}
clz = (Class extends Activity>) clz.getSuperclass();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 屏幕左侧右划返回容器 ,
*
* @author Young
*/
private class ViewContainer extends LinearLayout {
private int leftMargin;
private VelocityTracker tracker;
private float startX;
private float startY;
public ViewContainer(Context context) {
super(context);
leftMargin = DensityUtil.dip2px(35);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (isGestureOpen == false) {
return super.dispatchTouchEvent(ev);
}
switch (ev.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
//当满足下面条件时 视为 右划关闭手势
//起始按压位置x坐标小与leftMargin&& 向右滑动 && 向右滑动距离 > 竖直方向距离
if (startX < leftMargin && ev.getRawX() > startX && ev.getRawX() - startX > Math.abs(ev.getRawY() - startY)) {
//速度大于2500时关闭activity
tracker.computeCurrentVelocity(1000);
if (tracker.getXVelocity() > 2500) {
finish();
}
}
tracker.recycle();
break;
case MotionEvent.ACTION_DOWN:
startX = ev.getRawX();
startY = ev.getRawY();
tracker = VelocityTracker.obtain();
tracker.addMovement(ev);
break;
case MotionEvent.ACTION_MOVE:
tracker.addMovement(ev);
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isGestureOpen == false) {
return super.onTouchEvent(event);
}
return true;
}
}
}
上面代码是整个BaseActivity的代码,只封装了这几个,比如说在里面封装6.0以上权限或者网络提示框也可以在这儿设置封装,也可以在网络层封装,看自己习惯用法和需求
public class DensityUtil {
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(float dpValue) {
// 布局预览需要,try{}catch
try {
final float scale = App.getInstance().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (int) dpValue;
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(float pxValue) {
final float scale = App.getInstance().getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int screenHeigh() {
WindowManager wm = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE);
return wm.getDefaultDisplay().getHeight();
}
public static int screenWidth() {
WindowManager wm = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE);
return wm.getDefaultDisplay().getWidth();
}
public static int dip2pxs(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
public class App extends Application {
private static App app;
public static App getInstance() {
return app;
}
@Override
public void onCreate() {
super.onCreate();
app = this;
}
}
package com.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.base.BaseActivity;
public class MainActivity extends BaseActivity {
private Button btnStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setStatusBarColor(R.color.colorPrimaryDark);//状态栏颜色
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnStart:
Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_LONG).show();
break;
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.activity.MainActivity">
<Button
android:id="@+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button" />
LinearLayout>
效果图
编译器是Android studio
所有的代码都在这儿了