使用BaseActivity可以封装一些重复代码例如设置标题栏颜色,封装一些工具类...

主要功能:

  1. 封装Toast

新建一个BaseActivity继承自Activity

package com.onepilltest;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast; import com.onepilltest.util.KeyboardUtils;
import com.onepilltest.util.StatusBarUtil; /**
* 封装Activity用于管理所有Activity
*/ public abstract class BaseActivity extends Activity { /***是否显示标题栏*/
private boolean isshowtitle = true;
/***是否显示标题栏*/
private boolean isshowstate = true;
/***封装toast对象**/
private static Toast toast;
/***获取TAG的activity名称**/
protected final String TAG = this.getClass().getSimpleName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(intiLayout());
//初始化状态栏
{
//当FitsSystemWindows设置 true 时,会在屏幕最上方预留出状态栏高度的 padding
StatusBarUtil.setRootViewFitsSystemWindows(this,true);
//设置状态栏透明
StatusBarUtil.setTranslucentStatus(this);
//一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
//所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
//如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
//这样半透明+白=灰, 状态栏的文字能看得清
StatusBarUtil.setStatusBarColor(this,0x55000000);
}
}
//初始化控件
initView();
//设置数据
initData();
} /**
* 设置布局
*
* @return
*/
public abstract int intiLayout(); /**
* 初始化布局
*/
public abstract void initView(); /**
* 设置数据
*/
public abstract void initData(); public static String Help(){
String str = "\n-->\n";
str += "丨------------------------------\n";
str += "丨设置屏幕横竖屏切换:setScreenRoate(Boolean screenRoate) true 竖屏 false 横屏"+"\n";
str += "丨显示长toast:toastLong(String msg) String msg"+"\n";
str += "丨显示短toast:toastShort(String msg)"+"\n";
str += "丨页面跳转:startActivity(Class<?> clz)"+"\n";
str += "丨携带数据的页面跳转:startActivity(Class<?> clz, Bundle bundle)"+"\n";
str += "丨* * *设置EditView和Activity的互动* * *"+"\n";
str += "丨传入EditText的Id:重写hideSoftByEditViewIds()"+"\n";
str += "丨传入要过滤的View:filterViewByIds()"+"\n";
str += "丨* * * * * * * * * * * * * * * * * * *"+"\n";
str += "丨-----------------------------\n";
Log.e("BaseActivity_Help",str);
return str;
} /**
* 设置屏幕横竖屏切换
* @param screenRoate true 竖屏 false 横屏
*/
private void setScreenRoate(Boolean screenRoate) {
if (screenRoate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏模式
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} /**
* 显示长toast
* @param msg
*/
public void toastLong(String msg){
if (null == toast) {
toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setText(msg);
toast.show();
} else {
toast.setText(msg);
toast.show();
}
} /**
* 显示短toast
* @param msg
*/
public void toastShort(String msg){
if (null == toast) {
toast = new Toast(this);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(msg);
toast.show();
} else {
toast.setText(msg);
toast.show();
}
} /**
* [页面跳转]
* @param clz
*/
public void startActivity(Class<?> clz) {
startActivity(clz, null);
} /**
* [携带数据的页面跳转]
*
* @param clz
* @param bundle
*/
public void startActivity(Class<?> clz, Bundle bundle) {
Intent intent = new Intent();
intent.setClass(this, clz);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
} /**
* [含有Bundle通过Class打开编辑界面]
*
* @param cls
* @param bundle
* @param requestCode
*/
public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivityForResult(intent, requestCode);
} /**
* 以下是关于软键盘的处理
*/ /**
* 清除editText的焦点
*
* @param v 焦点所在View
* @param ids 输入框
*/
public void clearViewFocus(View v, int... ids) {
if (null != v && null != ids && ids.length > 0) {
for (int id : ids) {
if (v.getId() == id) {
v.clearFocus();
break;
}
}
}
} /**
* 隐藏键盘
*
* @param v 焦点所在View
* @param ids 输入框
* @return true代表焦点在edit上
*/
public boolean isFocusEditText(View v, int... ids) {
if (v instanceof EditText) {
EditText et = (EditText) v;
for (int id : ids) {
if (et.getId() == id) {
return true;
}
}
}
return false;
} //是否触摸在指定view上面,对某个控件过滤
public boolean isTouchView(View[] views, MotionEvent ev) {
if (views == null || views.length == 0) {
return false;
}
int[] location = new int[2];
for (View view : views) {
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (ev.getX() > x && ev.getX() < (x + view.getWidth())
&& ev.getY() > y && ev.getY() < (y + view.getHeight())) {
return true;
}
}
return false;
} @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (isTouchView(filterViewByIds(), ev)) {
return super.dispatchTouchEvent(ev);
}
if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0) {
return super.dispatchTouchEvent(ev);
}
View v = getCurrentFocus();
if (isFocusEditText(v, hideSoftByEditViewIds())) {
KeyboardUtils.hideInputForce(this);
clearViewFocus(v, hideSoftByEditViewIds());
}
}
return super.dispatchTouchEvent(ev);
} /**
* 传入EditText的Id
* 没有传入的EditText不做处理
*
* @return id 数组
*/
public int[] hideSoftByEditViewIds() {
return null;
} /**
* 传入要过滤的View
* 过滤之后点击将不会有隐藏软键盘的操作
*
* @return id 数组
*/
public View[] filterViewByIds() {
return null;
} /*实现案例===============================================================================================*/ // @Override
// public int[] hideSoftByEditViewIds() {
// int[] ids = {R.id.et_company_name, R.id.et_address};
// return ids;
// }
//
// @Override
// public View[] filterViewByIds() {
// View[] views = {mEtCompanyName, mEtAddress};
// return views;
// } }

工具类KeyboardUtils

package com.onepilltest.util;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText; import com.onepilltest.BaseActivity;
import com.onepilltest.R; import static android.content.Context.INPUT_METHOD_SERVICE; /**
* @author sunyaxi
* @date 2016/11/17.
*/
public class KeyboardUtils { /**
* 动态隐藏软键盘
*/
public static void hideSoftInput(Activity activity) {
View view = activity.getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputManger = (InputMethodManager) activity
.getSystemService(INPUT_METHOD_SERVICE);
inputManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} /**
* 动态隐藏软键盘
*/
public static void hideSoftInput(Context context, View view) {
view.clearFocus();
InputMethodManager inputManger = (InputMethodManager) context
.getSystemService(INPUT_METHOD_SERVICE);
inputManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
} /**
* 动态显示软键盘
*/
public static void showSoftInput(Context context, EditText edit) {
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(INPUT_METHOD_SERVICE);
inputManager.showSoftInput(edit, 0);
} /**
* 切换键盘显示与否状态
*/
public static void toggleSoftInput(Context context, EditText edit) {
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
} /**
* 点击屏幕空白区域隐藏软键盘(方法1)
* 在onTouch中处理,未获焦点则隐藏
* 参照以下注释代码
*/
public static void clickBlankArea2HideSoftInput0() {
Log.i("tips", "U should copy the following code.");
/*
@Override
public boolean onTouchEvent (MotionEvent event){
if (null != this.getCurrentFocus()) {
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
return super.onTouchEvent(event);
}
*/
} /**
* 点击屏幕空白区域隐藏软键盘(方法2)
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
* 需重写dispatchTouchEvent
* 参照以下注释代码
*/
public static void clickBlankArea2HideSoftInput1() {
Log.i("tips", "U should copy the following code.");
/*
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideKeyboard(v, ev)) {
hideKeyboard(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
// 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
return !(event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom);
}
return false;
}
// 获取InputMethodManager,隐藏软键盘
private void hideKeyboard(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
*/
} /**
* des:隐藏软键盘,这种方式参数为activity
*
* @param activity
*/
public static void hideInputForce(Activity activity) {
if (activity == null || activity.getCurrentFocus() == null)
return; ((InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(activity.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}

将自己的Activity继承BaseActivity

public class SettingActivity extends BaseActivity {

Android:自定义BaseActivity基类的更多相关文章

  1. Android 自定义Activity基类与TitleBar

    我们在开发App的时候有时候碰到多个界面有一个共同点的时候,比如,都有相同的TitleBar,并且TitleBar可以设置显示的文字.TitleBar上的点击事件,如果给每一个Activity都写一遍 ...

  2. Android 自定义EditText实现类iOS风格搜索框

    最近在项目中有使用到搜索框的地方,由于其样式要求与iOS的UISearchBar的风格一致.默认情况下,搜索图标和文字是居中的,在获取焦点的时候,图标和文字左移.但是在Android是并没有这样的控件 ...

  3. WPF自学入门(九)WPF自定义窗口基类

    今天简单记录一个知识点:WPF自定义窗口基类,常用winform的人知道,winform的窗体继承是很好用的,写一个基础窗体,直接在后台代码改写继承窗体名.但如果是WPF要继承窗体,我个人感觉没有理解 ...

  4. WPF 之 创建继承自Window 基类的自定义窗口基类

    开发项目时,按照美工的设计其外边框(包括最大化,最小化,关闭等按钮)自然不同于 Window 自身的,但窗口的外边框及窗口移动.最小化等标题栏操作基本都是一样的.所以通过查看资料,可按如下方法创建继承 ...

  5. WPF自定义窗口基类

    WPF自定义窗口基类时,窗口基类只定义.cs文件,xaml文件不定义.继承自定义窗口的类xaml文件的根节点就不再是<Window>,而是自定义窗口类名(若自定义窗口与继承者不在同一个命名 ...

  6. Android中的基类—抽取出来公共的方法

    在Android中,一般来说一个应用会存在几十个页面,并且一个应用一般也会使用一个特定的主题,其中的页面的风格也是一致的,并且页面中的动画效果.页面的切换效果等也应该保持同样的风格,那么就需要一个基类 ...

  7. (转)Android中的基类—抽取出来公共的方法

    在Android中,一般来说一个应用会存在几十个页面,并且一个应用一般也会使用一个特定的主题,其中的页面的风格也是一致的,并且页面中的动画效果.页面的切换效果等也应该保持同样的风格,那么就需要一个基类 ...

  8. How to: Implement a Custom Base Persistent Class 如何:实现自定义持久化基类

    XAF ships with the Business Class Library that contains a number of persistent classes ready for use ...

  9. Android 自定义Dialog工具类

    由于项目的需要,系统的弹出框已经不能满足我们的需求,我们需要各式各样的弹出框,这时就需要我们去自定义弹出框了. 新建布局文件 dialog_layout.xml,将下面内容复制进去 <?xml ...

随机推荐

  1. 使用onload和setTimeout、setInterval来实现当前的时间

    1.在body里面使用onload和在函数中使用setTimeout来实现当前的日期时间不断变化 2.在script中直接是用setInterval实现当前实现的日期时间不断变化 <!DOCTY ...

  2. apply()方法和call()介绍

    我们发现apply()和call()的真正用武之地是能够扩充函数赖以运行的作用域. 1.call,apply都属于Function.prototype的一个方法,它是JavaScript引擎内在实现的 ...

  3. 2020年Web前端开发工程师市场怎么样?学会什么技术才能拿到高薪

    几乎整个互联网行业都缺前端工程师,不仅在刚起步的创业公司,对上市公司乃至巨头这个问题也一样存在.据统计,国外的前端开发人员和后端开发人员比例约1:1,但是在国内比例却在1:3以下, Web前端开发职位 ...

  4. YOLOV4源码详解

    一. 整体架构 整体架构和YOLO-V3相同(感谢知乎大神@江大白),创新点如下: 输入端 --> Mosaic数据增强.cmBN.SAT自对抗训练: BackBone --> CSPDa ...

  5. css常用的简写技巧_css background简写、css border 简写、css font属性简写等

    css样式中有很多简写方式,比如:设置背景,字体,边框,盒子等.我们都可以把css代码合并为一行,这篇文章将总结有哪些属性支持css简写. 1.背景background属性 background-co ...

  6. 浏览器缓存_HTTP强缓存和协商缓存

    浏览器缓存 浏览器缓存是浏览器在本地磁盘对用户最近请求过的文档进行存储,当访问者再次访问同一页面时,浏览器就可以直接从本地磁盘加载文档. 所以根据上面的特点,浏览器缓存有下面的优点: 减少冗余的数据传 ...

  7. JS学习研究

    //1.undefined 是派生自null的 //alert(undefined == null); //alert(undefined === null); ////结果 true false / ...

  8. WPF中国地图

    实现鼠标移动到某个地区显示Popup弹框 1,地图 <Grid Margin="0,0,0,0" Grid.Row="1"> <Path St ...

  9. day78 作业

    目录 1 在作业.html的代码基础上,完成商品数量的加减,注意商品数量如果低于0个,则自动删除当前商品 2 在作业.html的代码基础仧,完成购物车总价格的计算 3 使用ajax获取北京天气,并把昨 ...

  10. 数据可视化之powerBI技巧(二十三)Power BI可视化技巧,使用DAX自定义时间轴

    ​按照自然日历来展现疫情数据时,是这样的效果, 由于各个国家的疫情爆发时间不一致,按自然日期坐标轴很难比较各个国家的蔓延速度. 如果各个国家都从蔓延日开始统计,展示之后每日的确诊人数,就是同样的时间轴 ...