Android:自定义BaseActivity基类
使用BaseActivity可以封装一些重复代码例如设置标题栏颜色,封装一些工具类...
主要功能:
- 封装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();@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(intiLayout());//初始化状态栏{//当FitsSystemWindows设置 true 时,会在屏幕最上方预留出状态栏高度的 paddingStatusBarUtil.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;}@Overridepublic 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.");/*@Overridepublic 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.");/*@Overridepublic 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基类相关推荐
- android mvp框架基类,Android MVP架构项目搭建封装,基类封装
综述 对于MVP (Model View Presenter)架构是从著名的MVC(Model View Controller)架构演变而来的.而对于Android应用的开发中本身可视为一种MVC架构 ...
- android单线字体,Android自定义字体
在main文件夹下,新建assets/fonts文件,添加.otf文件 image.png 字体工具类 import android.app.Application; import android.g ...
- Qt (高仿Visio)流程图组件开发(三) 图元基类如何定义,流程图多种图元类型实现
文章目录 本系列目录 前言 一.图元基类的定义 1.图元信息基类结构体 2.图元位置 3.父子对象关系 二.自定义图元实现 1.自定义图元基类(FlowchartGraphicsItem)与Qt原生图 ...
- Android仿人人客户端(v5.7.1)——项目框架新做的调整描述(项目中基类java源码)...
转载请标明出处:http://blog.csdn.net/android_ls/article/details/8909068 声明:没看过仿人人android客户端系列博文,前面的相关文章的朋友,请 ...
- Android 获取通讯录联系人,打开通讯录获取联系人信息;整个流程封装在基类中;
打开原生通讯录获取联系人姓名和手机号 1.获取通讯录权限: <!--访问通讯录--><uses-permission android:name="android.permi ...
- android自定义View学习(一)----创建一个视图类
创建一个视图类 精心设计的自定义视图与其他精心设计的类非常相似.它使用易于使用的界面封装了一组特定的功能,它可以高效地使用CPU和内存,等等.不过,作为一个设计良好的班级,自定义视图应该: 符合And ...
- 解密android日志xlog,安卓开发技巧2:自定义日志工具类XLog的实现
安卓开发技巧二:自定义日志工具类XLog的实现 我们在开发过程中,打印日志是必不可少的一个调试环节,然而,直接使用系统自带的Log日志类,并不能满足我们实际项目的需求:假如我们现在在开发一款比较大的项 ...
- python中的序列类型数据结构元素的切片操作_PythonI/O进阶学习笔记_4.自定义序列类(序列基类继承关系/可切片对象/推导式)...
前言: 本文代码基于python3 Content: 1.python中的序列类分类 2. python序列中abc基类继承关系 3. 由list的extend等方法来看序列类的一些特定方法 4. l ...
- Android自定义UI陷阱:LayoutInflater.from().inflate()一定不能工作在父类或虚类里
问题背景:有一些UI具有共性,比如常见的app第一次运行时出现的各种指示框,告诉你往哪搓是调音量的,往哪点是调屏幕亮度的,当点击这些VIew,则其自动消失.或者一动时间后,自动消失.另外一个问题是,不 ...
最新文章
- 化繁为简,一张图看懂梯度、散度、旋度、Jacobian、Hessian和Laplacian
- 《智能路由器开发指南》——1.1 OpenWrt简介
- 解决IntelliJ无法导入maven包的问题
- 计算机二级access选择题知识点总结,全国计算机二级Access考试重点题型汇总(选择题).doc...
- openlayer 图层上下_OpenLayers实现图层切换控件
- windows linux 子系统折腾记
- python es 数据库 ik_Linux系统:centos7下搭建ElasticSearch中间件,常用接口演示
- 用jQuery实现简单的加入收藏页面的功能
- 深大计算机系有金工实习吗,金工实习报告答案深圳大学拿A答案(精选).pdf
- 试题5 算法训练 猴子吃包子
- Linux chmod权限详解
- matlab vl_feat,matlab 安装 vl_feat
- UML类图画法全程解析
- CSR是什么样的公司?CSR蓝牙芯片有何过人之处?
- phpstudy如何创建mysql_PHPStudy怎样创建数据库
- u盘写保护无法格式化的修复
- 网络文件系统——上(samba,NFS,实现网络共享文件)
- (MIUI)小米手机录音丢失找回
- 多轴控制玻璃行业程序 相机 ST LAD SFC
- 关于医学和计算机的论文,计算机医学管理论文
热门文章
- 从JDK源码角度看Short
- Chrome 浏览器中,使用 Shift + Esc 打开任务管理器 / 浏览器进程管理 结束进程
- 包信封问题 以及 最长有序子序列问题
- 【FlexSim2019】自学笔记:交通工具路径设置 | NetworkNode | 操作员固定路径 | 叉车固定路径
- 计算机网络 职中,职中计算机网络基础期中考试试卷.pdf
- web服务启动后mysql崩溃_让Web站点崩溃最常见的七大原因
- SAP 录屏BDC使用—实例
- js动态加载css文件和js文件的方法
- 如何用MEF实现Asp.Net MVC框架
- javascript在IE和Firefox中兼容性问题