使用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. DOM-BOM-EVENT(6)

    6.BOM 6.1.什么是BOM? BOM(Browse Object Model),浏览器对象模型,没有相关标准,是约定俗成的东西,定义了一些操作浏览器的方法和属性,大部分方法都是通过window对 ...

  2. Buy a Ticket 【最短路】

    题目 Musicians of a popular band "Flayer" have announced that they are going to "make t ...

  3. Spring中使用注解时启用<context:component-scan/>

    在spring中使用注解方式时需要在spring配置文件中配置组件扫描器:http://blog.csdn.net/j080624/article/details/56277315 <conte ...

  4. BZOJ3242 快餐店

    原题传送门 题意 给定一个n条边n个点的连通图,求该图的某一点在该图距离最远的点距离它的距离的最小值. 题解 显然,答案是\(\frac {原图直径}{2}\). 本体的图有 \(n\) 个点 \(n ...

  5. Windows使用VNC远程连接Linux桌面系统

    sudo yum -y install tigervnc-server  #安装 su - your_user #切换用户 vncpasswd #设置密码 sudo cp /lib/systemd/s ...

  6. 猿灯塔:关于Java面试,你应该准备这些知识点

    自天子以至于庶人,壹是皆以修身为本 <礼记·大学> 马老师说过,员工的离职原因很多,只有两点最真实: 钱,没给到位 心,受委屈了 当然,我是想换个平台,换个方向,想清楚为什么要跳槽,如果真 ...

  7. MySQL索引 索引分类 最左前缀原则 覆盖索引 索引下推 联合索引顺序

    MySQL索引 索引分类 最左前缀原则 覆盖索引 索引下推 联合索引顺序   What's Index ? 索引就是帮助RDBMS高效获取数据的数据结构. 索引可以让我们避免一行一行进行全表扫描.它的 ...

  8. cf1216E2 Numerical Sequence (hard version)(思维)

    cf1216E2 Numerical Sequence (hard version) 题目大意 一个无限长的数字序列,其组成为\(1 1 2 1 2 3 1.......1 2 ... n...\), ...

  9. 线性DP之免费馅饼

    题目 思路 线性DP,思路很容易就能想到,f[i][k]数组定义为第i秒在k位置时从上一位置j转移过来的最优解,易得f[i][k]=max(f[i][k],f[i-1][j]+search(i,k)) ...

  10. 二叉搜索树的后序遍历序列(剑指offer-23)

    题目描述 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则输出Yes,否则输出No.假设输入的数组的任意两个数字都互不相同. 题目解析 采用分治法的思想,找到根结点.左子树的序 ...