当前位置: 移动技术网 > 移动技术>移动开发>Android > Android输入法与表情面板切换时的界面抖动问题解决方法

Android输入法与表情面板切换时的界面抖动问题解决方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

昨天琢磨了下android的输入法弹出模式,突然发现利用动态切换输入法的弹出模式可以解决输入法抖动的问题。具体是怎样的抖动呢?我们先看微博的反面教材。

【具体表现为:表情面板与输入法面板高度不一致,从而导致弹出输入法(layout被挤压)时,同时又需要隐藏表情面板(layout被拉升),最终让界面产生了高度差抖动,所以在切换时明显会有不大好的抖动体验)】

使用了解决抖动的解决方案后,效果如下:

【这样的方案明显比微博的切换更平滑】

老样子,先说思路。主要我们要用到两个输入法弹出模式,分别是:adjustresize(调整模式) 、adjustnothing(不做任何调整) 。(更多介绍请参看我的上一篇文章:输入法弹出参数分析)

1.初始情况时(键盘和表情面板都未展开):我们为表情面板设置一个默认高度(因为我们还不知道键盘有多高)并将输入发弹出模式设置为adjustresize模式。
2.当我们点击了edittext时,系统将会弹出输入法,由于之前我们设置的模式为adjustresize,因此,输入法会挤压layout,并且挤压的高度最终会固定到一个值(键盘的高度),当我们检测到挤压后,将这个挤压差值(也就是键盘高度)记录下来,作为表情面板的新高度值。于此同时,我们将表情面板隐藏。
3.当我们点击了表情按钮时,我们需要先判断输入法是否已展开。
1)如果已经展开,那么我们的任务是将键盘平滑隐藏并显示表情面板。具体做法为:先将activity的输入法弹出模式设置为adjustnothing,然后将上一步记录下来的键盘高度作为表情面板的高度,再将表情面板显示,此时由于键盘弹出模式为adjustnothing,所以键盘不会有任何抖动,并且由于表情面板与键盘等高,因此edittext也不会下移,最后将输入法隐藏。
2)如果输入法未展开,我们再判断表情面板是否展开,如果展开了就隐藏并将输入法弹出模式归位为adjustresize,如果未展开就直接显示并将输入法弹出模式设置为adjustnothing。
大致的实现思路就是上面说到的,但是,既然都准备动手做帮助类了,就顺便将点击空白处折叠键盘和表情面板一起做了。具体实现思路为:在activity的decorview上面遮罩一层framelayout,用于监听触摸的aciton_down事件,如果在输入范围之外,则折叠表情面板和键盘。示意图如下:

该说的说完了,开动。

1、创建inputmethodutils类,构造方法需要传递activity参数,并申明所需要的成员变量,并实现view.onclicklistener接口(因为我们要监听表情按钮的点击事件)。代码如下:

public class inputmethodutils implements view.onclicklistener {
  // 键盘是否展开的标志位
  private boolean siskeyboardshowing;
  // 键盘高度变量
  private int skeyboardheight = 0;
  // 绑定的activity
  private activity activity;
  /**
   * 构造函数
   * 
   * @param activity
   *      需要处理输入法的当前的activity
   */
  public inputmethodutils(activity activity) {
    this.activity = activity;
    //displayutils为屏幕尺寸工具类
    displayutils.init(activity);
    // 默认键盘高度为267dp
    setkeyboardheight(displayutils.dp2px(267));
  }
  @override
  public void onclick(view v) {
  }
}

//displayutils的实现代码为:

/**
 * 屏幕参数的辅助工具类。例如:获取屏幕高度,宽度,statusbar的高度,px和dp互相转换等
 * 【注意,使用之前一定要初始化!一次初始化就ok(建议app启动时进行初始化)。 初始化代码 displayutils.init(context)】
 * @author 蓝亭书序
 */
private static class displayutils {
  // 四舍五入的偏移值
  private static final float round_ceil = 0.5f;
  // 屏幕矩阵对象
  private static displaymetrics sdisplaymetrics;
  // 资源对象(用于获取屏幕矩阵)
  private static resources sresources;
  // statusbar的高度(由于这里获取statusbar的高度使用的反射,比较耗时,所以用变量记录)
  private static int statusbarheight = -1;
  /**
   * 初始化操作
   * 
   * @param context
   *      context上下文对象
   */
  public static void init(context context) {
    sdisplaymetrics = context.getresources().getdisplaymetrics();
    sresources = context.getresources();
  }

  /**
   * 获取屏幕高度 单位:像素
   * 
   * @return 屏幕高度
   */
  public static int getscreenheight() {
    return sdisplaymetrics.heightpixels;
  }

  /**
   * 获取屏幕宽度 单位:像素
   * 
   * @return 屏幕宽度
   */
  public static float getdensity() {
    return sdisplaymetrics.density;
  }

  /**
   * dp 转 px
   * 
   * @param dp
   *      dp值
   * @return 转换后的像素值
   */
  public static int dp2px(int dp) {
    return (int) (dp * getdensity() + round_ceil);
  }

  /**
   * 获取状态栏高度
   * 
   * @return 状态栏高度
   */
  public static int getstatusbarheight() {
    // 如果之前计算过,直接使用上次的计算结果
    if (statusbarheight == -1) {
      final int defaultheightindp = 19;// statusbar默认19dp的高度
      statusbarheight = displayutils.dp2px(defaultheightindp);
      try {
        class<?> c = class.forname("com.android.internal.r$dimen");
        object obj = c.newinstance();
        field field = c.getfield("status_bar_height");
        statusbarheight = sresources.getdimensionpixelsize(integer
            .parseint(field.get(obj).tostring()));
      } catch (exception e) {
        e.printstacktrace();
      }
    }
    return statusbarheight;
  }
}

【搬砖去了,等会继续写… … 】好了,继续写… …

2、在继续往下写之前,我们得考虑如何设计表情按钮、表情按钮点击事件、表情面板之间的问题。我的做法是创建一个viewbinder内部类。(因为在逻辑上来说,这三个属于一体的)
viewbinder的实现代码如下:

/**
 * 用于控制点击某个按钮显示或者隐藏“表情面板”的绑定bean对象。<br/>
 * 例如:我想点击“表情”按钮显示“表情面板”,我就可以这样做:<br/>
 * viewbinder viewbinder = new viewbinder(btn_emotion,emotionpanel);<br/>
 * 这样就创建出了一个viewbinder对象<br/>
 * <font color='red'>【注意事项,使用此类时,千万不要使用trigger的setonclicklistener来监听事件(
 * 使用ontriggerclicklistener来代替),也不要使用settag来设置tag,否则会导致使用异常】</font>
 * @author 蓝亭书序
 */
public static class viewbinder {
  private view trigger;//表情按钮对象
  private view panel;//表情面板对象
  //替代的监听器
  private ontriggerclicklistener listener;

  /**
   * 创建viewbinder对象<br/>
   * 例如:我想点击“表情”按钮显示“表情面板”,我就可以这样做:<br/>
   * viewbinder viewbinder = new
   * viewbinder(btn_emotion,emotionpanel,listener);<br/>
   * 这样就创建出了一个viewbinder对象
   * 
   * @param trigger
   *      触发对象
   * @param panel
   *      点击触发对象需要显示/隐藏的面板对象
   * @param listener
   *      trigger点击的监听器(千万不要使用setonclicklistener,否则会覆盖本工具类的监听器)
   */
  public viewbinder(view trigger, view panel,
      ontriggerclicklistener listener) {
    this.trigger = trigger;
    this.panel = panel;
    this.listener = listener;
    trigger.setclickable(true);
  }
  @override
  public boolean equals(object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getclass() != obj.getclass())
      return false;
    viewbinder other = (viewbinder) obj;
    if (panel == null) {
      if (other.panel != null)
        return false;
    } else if (!panel.equals(other.panel))
      return false;
    if (trigger == null) {
      if (other.trigger != null)
        return false;
    } else if (!trigger.equals(other.trigger))
      return false;
    return true;
  }
  public ontriggerclicklistener getlistener() {
    return listener;
  }
  public void setlistener(ontriggerclicklistener listener) {
    this.listener = listener;
  }
  public view gettrigger() {
    return trigger;
  }
  public void settrigger(view trigger) {
    this.trigger = trigger;
  }
  public view getpanel() {
    return panel;
  }
  public void setpanel(view panel) {
    this.panel = panel;
  }
}

其中ontriggerclicklistener是为了解决trigger占用监听器的问题(我们内部逻辑需要占用监听器,如果外部想实现额外的点击逻辑不能再为trigger添加监听器,所以使用ontriggerclicklistener来代替原原声的onclicklistener)。ontriggerclicklistener为一个接口,实现代码如下:

/**
 * viewbinder的触发按钮点击的监听器
 * @author 蓝亭书序
 */
public static interface ontriggerclicklistener {
  /**
   * 点击事件的回调函数 
   * @param v 被点击的按钮对象
   */
  public void onclick(view v);
}

3、实现了viewbinder后,我们还需要实现一个遮罩view,用于监听action_down事件。代码如下:

/**
 * 点击软键盘区域以外自动关闭软键盘的遮罩view
 * @author 蓝亭书序
 */
private class closekeyboardonoutsidecontainer extends framelayout {

  public closekeyboardonoutsidecontainer(context context) {
    this(context, null);
  }

  public closekeyboardonoutsidecontainer(context context,
      attributeset attrs) {
    this(context, attrs, 0);
  }

  public closekeyboardonoutsidecontainer(context context,
      attributeset attrs, int defstyle) {
    super(context, attrs, defstyle);
  }

  /*如果不知道这个方法的作用的话,需要了解下android的事件分发机制哈,如果有时间我也可以写个文章介绍下。dispatchtouchevent方法主要是viewgroup在事件分发之前进行事件进行判断,如果返回true表示此viewgroup拦截此事件,这个事件将不会传递给他的子view,如果返回false,反之。*/
  @override
  public boolean dispatchtouchevent(motionevent event) {
  //这段逻辑不复杂,看一遍应该就懂
    boolean iskeyboardshowing = iskeyboardshowing();
    boolean isemotionpanelshowing = haspanelshowing();
    if ((iskeyboardshowing || isemotionpanelshowing)
        && event.getaction() == motionevent.action_down) {
      int touchy = (int) (event.gety());
      int touchx = (int) (event.getx());
      if (istouchkeyboardoutside(touchy)) {
        if (iskeyboardshowing) {
          hidekeybordandsetflag(activity.getcurrentfocus());
        }
        if (isemotionpanelshowing) {
          closeallpanels();
        }
      }
      if (istouchedfoucusview(touchx, touchy)) {
        // 如果点击的是输入框(会弹出输入框),那么延时折叠表情面板
        postdelayed(new runnable() {
          @override
          public void run() {
            setkeyboardshowing(true);
          }
        }, 500);
      }
    }
    return super.ontouchevent(event);
  }
}

/**
 * 是否点击软键盘和输入法外面区域
 * @param activity
 *      当前activity
 * @param touchy
 *      点击y坐标(不包括statusbar的高度)
 */
private boolean istouchkeyboardoutside(int touchy) {
  view foucusview = activity.getcurrentfocus();
  if (foucusview == null) {
    return false;
  }
  int[] location = new int[2];
  foucusview.getlocationonscreen(location);
  int edity = location[1] - displayutils.getstatusbarheight();
  int offset = touchy - edity;
  if (offset > 0 && offset < foucusview.getmeasuredheight()) {
    return false;
  }
  return true;
}
/**
 * 是否点击的是当前焦点view的范围
 * @param x
 *      x方向坐标
 * @param y
 *      y方向坐标(不包括statusbar的高度)
 * @return true表示点击的焦点view,false反之
 */
private boolean istouchedfoucusview(int x, int y) {
  view foucusview = activity.getcurrentfocus();
  if (foucusview == null) {
    return false;
  }
  int[] location = new int[2];
  foucusview.getlocationonscreen(location);
  int foucusviewtop = location[1] - displayutils.getstatusbarheight();
  int offsety = y - foucusviewtop;
  if (offsety > 0 && offsety < foucusview.getmeasuredheight()) {
    int foucusviewleft = location[0];
    int foucusviewlength = foucusview.getwidth();
    int offsetx = x - foucusviewleft;
    if (offsetx >= 0 && offsetx <= foucusviewlength) {
      return true;
    }
  }
  return false;
}

4、准备工作做完,我们可以继续完善inputmethodutils类了,由于我们需要存储viewbinder对象(主要用于控制按钮和面板之间的关联关系),所以,我们还需要在inputmethodutils中申明一个集合。代码如下:

// 触发与面板对象集合(使用set可以自动过滤相同的viewbinder)
private set<viewbinder> viewbinders = new hashset<viewbinder>();

5、与viewbinders 随之而来的一些常用方法有必要写一下(例如折叠所有表情面板、获取当前哪个表情面板展开着等),代码如下:

/**
 * 添加viewbinder
 * @param viewbinder
 *      变长参数
 */
public void setviewbinders(viewbinder... viewbinder) {
  for (viewbinder vbinder : viewbinder) {
    if (vbinder != null) {
      viewbinders.add(vbinder);
      vbinder.trigger.settag(vbinder);
      vbinder.trigger.setonclicklistener(this);
    }
  }
  updateallpanelheight(skeyboardheight);
}
/**
 * 重置所有面板
 * @param dstpanel
 *      重置操作例外的对象
 */
private void resetotherpanels(view dstpanel) {
  for (viewbinder vbinder : viewbinders) {
    if (dstpanel != vbinder.panel) {
      vbinder.panel.setvisibility(view.gone);
    }
  }
}
/**
 * 关闭所有的面板
 */
public void closeallpanels() {
  resetotherpanels(null);
  //重置面板后,需要将输入法弹出模式一并重置
  updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
}
/**
 * 判断是否存在正在显示的面板
 * @return true表示存在,false表示不存在
 */
public boolean haspanelshowing() {
  for (viewbinder viewbinder : viewbinders) {
    if (viewbinder.panel.isshown()) {
      return true;
    }
  }
  return false;
}
/**
 * 更新所有面板的高度
 * @param height
 *      具体高度(单位px)
 */
private void updateallpanelheight(int height) {
  for (viewbinder vbinder : viewbinders) {
    viewgroup.layoutparams params = vbinder.panel.getlayoutparams();
    params.height = height;
    vbinder.panel.setlayoutparams(params);
  }
}

6、通过监听layout的变化来判断输入法是否已经展开。代码如下:

/**
 * 设置view树监听,以便判断键盘是否弹出。<br/>
 * 【只有当activity的windowsoftinputmode设置为adjustresize时才有效!所以我们要处理adjustnoting(不会引起layout的形变)的情况键盘监听(后文会提到)】
 */
private void detectkeyboard() {
  final view activityrootview = ((viewgroup) activity
      .findviewbyid(android.r.id.content)).getchildat(0);
  if (activityrootview != null) {
    viewtreeobserver observer = activityrootview.getviewtreeobserver();
    if (observer == null) {
      return;
    }
    observer.addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() {
      @override
      public void ongloballayout() {
        final rect r = new rect();
        activityrootview.getwindowvisibledisplayframe(r);
        int heightdiff = displayutils.getscreenheight()
            - (r.bottom - r.top);
        //layout形变超过键盘的一半表示键盘已经展开了
        boolean show = heightdiff >= skeyboardheight / 2;
        setkeyboardshowing(show);// 设置键盘是否展开状态
        if (show) {
          int keyboardheight = heightdiff
              - displayutils.getstatusbarheight();
          // 设置新的键盘高度
          setkeyboardheight(keyboardheight);
        }
      }
    });
  }
}

7、完成键盘的显示/隐藏和动态控制输入法弹出模式的常用方法。代码如下:

/**
 * 隐藏输入法
 * @param currentfocusview
 *      当前焦点view
 */
public static void hidekeyboard(view currentfocusview) {
  if (currentfocusview != null) {
    ibinder token = currentfocusview.getwindowtoken();
    if (token != null) {
      inputmethodmanager im = (inputmethodmanager) currentfocusview
          .getcontext().getsystemservice(
              context.input_method_service);
      im.hidesoftinputfromwindow(token, 0);
    }
  }
}
/**
 * 更新输入法的弹出模式(注意这是静态方法,可以直接当做工具方法使用)
 * @param activity 对应的activity
 * @param softinputmode
 * <br/>
 *      键盘弹出模式:windowmanager.layoutparams的参数有:<br/>
 *          可见状态: soft_input_state_unspecified,
 *      soft_input_state_unchanged, soft_input_state_hidden,
 *      soft_input_state_always_visible, or soft_input_state_visible.<br/>
 *          适配选项有: soft_input_adjust_unspecified,
 *      soft_input_adjust_resize, or soft_input_adjust_pan.
 */
public static void updatesoftinputmethod(activity activity,
    int softinputmode) {
  if (!activity.isfinishing()) {
    windowmanager.layoutparams params = activity.getwindow()
        .getattributes();
    if (params.softinputmode != softinputmode) {
      params.softinputmode = softinputmode;
      activity.getwindow().setattributes(params);
    }
  }
}

/**
 * 更新输入法的弹出模式(遇上面的静态方法的区别是直接使用的是绑定的activity对象)
 * 
 * @param softinputmode
 * <br/>
 *      键盘弹出模式:windowmanager.layoutparams的参数有:<br/>
 *          可见状态: soft_input_state_unspecified,
 *      soft_input_state_unchanged, soft_input_state_hidden,
 *      soft_input_state_always_visible, or soft_input_state_visible.<br/>
 *          适配选项有: soft_input_adjust_unspecified,
 *      soft_input_adjust_resize, or soft_input_adjust_pan.
 */
public void updatesoftinputmethod(int softinputmode) {
  updatesoftinputmethod(activity, softinputmode);
}

8、在构造方法中将这些组件都初始化,并做相关设置,代码如下:

/**
 * 构造函数
 * 
 * @param activity
 *      需要处理输入法的当前的activity
 */
public inputmethodutils(activity activity) {
  this.activity = activity;
  displayutils.init(activity);
  // 默认键盘高度为267dp
  setkeyboardheight(displayutils.dp2px(267));
  updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
  detectkeyboard();// 监听view树变化,以便监听键盘是否弹出
  enableclosekeyboardontouchoutside(activity);
}

/**
 1. 设置键盘的高度
 2. 
 3. @param keyboardheight
 4.      键盘的高度(px单位)
 */
private void setkeyboardheight(int keyboardheight) {
  skeyboardheight = keyboardheight;
  updateallpanelheight(keyboardheight);
}
/**
 5. 开启点击外部关闭键盘的功能(其实就是将遮罩view添加到decorview)
 6. 
 7. @param activity
 */
private void enableclosekeyboardontouchoutside(activity activity) {
  closekeyboardonoutsidecontainer framelayout = new closekeyboardonoutsidecontainer(
      activity);
  activity.addcontentview(framelayout, new viewgroup.layoutparams(
      viewgroup.layoutparams.match_parent,
      viewgroup.layoutparams.match_parent));
}

【突然有事,先写到这,等会来完善…】回来了,接着写。
上面的代码基本完成需求,需要重点说的是如何检测键盘弹出/隐藏状态的问题(有人可能会说用inputmethodmanager.isactive()啊,恩…反正我用有这个方法问题,他永远都给我返回true),下面简单介绍下如何实现的键盘的弹出和隐藏状态的检测。

1、如果当前输入法是adjustresize模式,那么我们直接可以用layout的形变监听即可实现,也就是之前detectkeyboard()实现的代码。

2、如果当前输入法是adjustnoting模式,这个就有点难处理了,因为没有形变可以监听。我的实现方式是:通过遮罩view判断action_down的坐标,如果该坐标落在输入框内(就是用户点击了输入框,此时系统将会弹出输入框),那么我们就可以认为键盘为弹出模式。代码体现在closekeyboardonoutsidecontainer的dispatchtouchevent()方法中。

到此,开发就告一段落了。按照惯例,完整代码如下:

/**
 * 解决输入法与表情面板之间切换时抖动冲突的控制辅助工具类(能做到将面板与输入法之间平滑切换).另外,具备点击空白处自动收起面板和输入法的功能.<br/>
 * 使用方法介绍如下:
 * <hr/>
 * <font color= 'red'>申明:【此类中,我们将表情面板选项、显示表情面板的按钮、表情面板按钮的点击事件
 * 作为一个整体,包装在viewbinder类中(点击表情面板按钮时,将会展开表情面 板 ) 】</font> <br/>
 * 因此,第一步,我们将需要操作的表情面板、按钮、事件绑定在一起,创建viewbinder类(可以是很多个)代码示例如下:<br/>
 * //如果不想监听按钮点击事件,之间将listener参数替换成null即可<br/>
 * viewbinder viewbinder1 = new viewbinder(btn_1,panel1,listener1);<br/>
 * viewbinder viewbinder2 = new viewbinder(btn_2,panel2,listener2);<br/>
 * ...<br/>
 * 第二步:创建inputmethodutils类<br/>
 * inputmethodutils inputmethodutils = new inputmethodutils(this);<br/>
 * 第三部:将viewbinder传递给inputmethodutils。<br/>
 * inputmethodutils.setviewbinders(viewbinder1,viewbinder2);//这个参数为动态参数,
 * 支持多个参数传递进来
 * <hr/>
 * 本类还提供两个常用的工具方法:<br/>
 * inputmethodutils.hidekeyboard();//用于隐藏输入法<br/>
 * inputmethodutils.updatesoftinputmethod();//用于将当前activity的输入法模式切换成指定的输入法模式
 * <br/>
 * 
 * @author 李长军 2016.11.26
 */
public class inputmethodutils implements view.onclicklistener {

  // 键盘是否展开的标志位
  private boolean siskeyboardshowing;
  // 键盘高度
  private int skeyboardheight = 0;
  // 绑定的activity
  private activity activity;
  // 触发与面板对象集合
  private set<viewbinder> viewbinders = new hashset<viewbinder>();

  /**
   * 构造函数
   * 
   * @param activity
   *      需要处理输入法的当前的activity
   */
  public inputmethodutils(activity activity) {
    this.activity = activity;
    displayutils.init(activity);
    // 默认键盘高度为267dp
    setkeyboardheight(displayutils.dp2px(267));
    updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
    detectkeyboard();// 监听view树变化,以便监听键盘是否弹出
    enableclosekeyboardontouchoutside(activity);
  }

  /**
   * 添加viewbinder
   * 
   * @param viewbinder
   *      变长参数
   */
  public void setviewbinders(viewbinder... viewbinder) {
    for (viewbinder vbinder : viewbinder) {
      if (vbinder != null) {
        viewbinders.add(vbinder);
        vbinder.trigger.settag(vbinder);
        vbinder.trigger.setonclicklistener(this);
      }
    }
    updateallpanelheight(skeyboardheight);
  }

  @override
  public void onclick(view v) {
    viewbinder viewbinder = (viewbinder) v.gettag();
    view panel = viewbinder.panel;
    resetotherpanels(panel);// 重置所有面板
    if (iskeyboardshowing()) {
      updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_nothing);
      panel.setvisibility(view.visible);
      hidekeybordandsetflag(activity.getcurrentfocus());
    } else if (panel.isshown()) {
      updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
      panel.setvisibility(view.gone);
    } else {
      updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
      panel.setvisibility(view.visible);
    }
    if (viewbinder.listener != null) {
      viewbinder.listener.onclick(v);
    }
  }

  /**
   * 获取键盘是否弹出
   * 
   * @return true表示弹出
   */
  public boolean iskeyboardshowing() {
    return siskeyboardshowing;
  }

  /**
   * 获取键盘的高度
   * 
   * @return 键盘的高度(px单位)
   */
  public int getkeyboardheight() {
    return skeyboardheight;
  }

  /**
   * 关闭所有的面板
   */
  public void closeallpanels() {
    resetotherpanels(null);
    updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
  }

  /**
   * 判断是否存在正在显示的面板
   * 
   * @return true表示存在,false表示不存在
   */
  public boolean haspanelshowing() {
    for (viewbinder viewbinder : viewbinders) {
      if (viewbinder.panel.isshown()) {
        return true;
      }
    }
    return false;
  }

  /**
   * 更新输入法的弹出模式
   * 
   * @param softinputmode
   * <br/>
   *      键盘弹出模式:windowmanager.layoutparams的参数有:<br/>
   *          可见状态: soft_input_state_unspecified,
   *      soft_input_state_unchanged, soft_input_state_hidden,
   *      soft_input_state_always_visible, or soft_input_state_visible.<br/>
   *          适配选项有: soft_input_adjust_unspecified,
   *      soft_input_adjust_resize, or soft_input_adjust_pan.
   */
  public void updatesoftinputmethod(int softinputmode) {
    updatesoftinputmethod(activity, softinputmode);
  }

  /**
   * 隐藏输入法
   * 
   * @param currentfocusview
   *      当前焦点view
   */
  public static void hidekeyboard(view currentfocusview) {
    if (currentfocusview != null) {
      ibinder token = currentfocusview.getwindowtoken();
      if (token != null) {
        inputmethodmanager im = (inputmethodmanager) currentfocusview
            .getcontext().getsystemservice(
                context.input_method_service);
        im.hidesoftinputfromwindow(token, 0);
      }
    }
  }

  /**
   * 更新输入法的弹出模式
   * 
   * @param activity
   * @param softinputmode
   * <br/>
   *      键盘弹出模式:windowmanager.layoutparams的参数有:<br/>
   *          可见状态: soft_input_state_unspecified,
   *      soft_input_state_unchanged, soft_input_state_hidden,
   *      soft_input_state_always_visible, or soft_input_state_visible.<br/>
   *          适配选项有: soft_input_adjust_unspecified,
   *      soft_input_adjust_resize, or soft_input_adjust_pan.
   */
  public static void updatesoftinputmethod(activity activity,
      int softinputmode) {
    if (!activity.isfinishing()) {
      windowmanager.layoutparams params = activity.getwindow()
          .getattributes();
      if (params.softinputmode != softinputmode) {
        params.softinputmode = softinputmode;
        activity.getwindow().setattributes(params);
      }
    }
  }

  /**
   * 隐藏键盘,并维护显示或不显示的逻辑
   * 
   * @param currentfocusview
   *      当前的焦点view
   */
  private void hidekeybordandsetflag(view currentfocusview) {
    siskeyboardshowing = false;
    hidekeyboard(currentfocusview);
  }

  /**
   * 重置所有面板
   */
  private void resetotherpanels(view dstpanel) {
    for (viewbinder vbinder : viewbinders) {
      if (dstpanel != vbinder.panel) {
        vbinder.panel.setvisibility(view.gone);
      }
    }
  }

  /**
   * 更新所有面板的高度
   * 
   * @param height
   *      具体高度
   */
  private void updateallpanelheight(int height) {
    for (viewbinder vbinder : viewbinders) {
      viewgroup.layoutparams params = vbinder.panel.getlayoutparams();
      params.height = height;
      vbinder.panel.setlayoutparams(params);
    }
  }

  /**
   * 设置键盘弹出与否状态
   * 
   * @param show
   *      true表示弹出,false表示未弹出
   */
  private void setkeyboardshowing(boolean show) {
    siskeyboardshowing = show;
    if (show) {
      resetotherpanels(null);
      updatesoftinputmethod(windowmanager.layoutparams.soft_input_adjust_resize);
    }
  }

  /**
   * 设置键盘的高度
   * 
   * @param keyboardheight
   *      键盘的高度(px单位)
   */
  private void setkeyboardheight(int keyboardheight) {
    skeyboardheight = keyboardheight;
    updateallpanelheight(keyboardheight);
  }

  /**
   * 是否点击软键盘和输入法外面区域
   * 
   * @param activity
   *      当前activity
   * @param touchy
   *      点击y坐标(不包括statusbar的高度)
   */
  private boolean istouchkeyboardoutside(int touchy) {
    view foucusview = activity.getcurrentfocus();
    if (foucusview == null) {
      return false;
    }
    int[] location = new int[2];
    foucusview.getlocationonscreen(location);
    int edity = location[1] - displayutils.getstatusbarheight();
    int offset = touchy - edity;
    if (offset > 0 && offset < foucusview.getmeasuredheight()) {
      return false;
    }
    return true;
  }

  /**
   * 是否点击的是当前焦点view的范围
   * 
   * @param x
   *      x方向坐标
   * @param y
   *      y方向坐标(不包括statusbar的高度)
   * @return true表示点击的焦点view,false反之
   */
  private boolean istouchedfoucusview(int x, int y) {
    view foucusview = activity.getcurrentfocus();
    if (foucusview == null) {
      return false;
    }
    int[] location = new int[2];
    foucusview.getlocationonscreen(location);
    int foucusviewtop = location[1] - displayutils.getstatusbarheight();
    int offsety = y - foucusviewtop;
    if (offsety > 0 && offsety < foucusview.getmeasuredheight()) {
      int foucusviewleft = location[0];
      int foucusviewlength = foucusview.getwidth();
      int offsetx = x - foucusviewleft;
      if (offsetx >= 0 && offsetx <= foucusviewlength) {
        return true;
      }
    }
    return false;
  }

  /**
   * 开启点击外部关闭键盘的功能
   * 
   * @param activity
   */
  private void enableclosekeyboardontouchoutside(activity activity) {
    closekeyboardonoutsidecontainer framelayout = new closekeyboardonoutsidecontainer(
        activity);
    activity.addcontentview(framelayout, new viewgroup.layoutparams(
        viewgroup.layoutparams.match_parent,
        viewgroup.layoutparams.match_parent));
  }

  /**
   * 设置view树监听,以便判断键盘是否弹出。<br/>
   * 【只有当activity的windowsoftinputmode设置为adjustresize时才有效】
   */
  private void detectkeyboard() {
    final view activityrootview = ((viewgroup) activity
        .findviewbyid(android.r.id.content)).getchildat(0);
    if (activityrootview != null) {
      viewtreeobserver observer = activityrootview.getviewtreeobserver();
      if (observer == null) {
        return;
      }
      observer.addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() {
        @override
        public void ongloballayout() {
          final rect r = new rect();
          activityrootview.getwindowvisibledisplayframe(r);
          int heightdiff = displayutils.getscreenheight()
              - (r.bottom - r.top);
          boolean show = heightdiff >= skeyboardheight / 2;
          setkeyboardshowing(show);// 设置键盘是否展开状态
          if (show) {
            int keyboardheight = heightdiff
                - displayutils.getstatusbarheight();
            // 设置新的键盘高度
            setkeyboardheight(keyboardheight);
          }
        }
      });
    }
  }

  /**
   * viewbinder的触发按钮点击的监听器
   * 
   * @author 李长军
   * 
   */
  public static interface ontriggerclicklistener {
    /**
     * 
     * @param v
     */
    public void onclick(view v);
  }

  /**
   * 用于控制点击某个按钮显示或者隐藏“表情面板”的绑定bean对象。<br/>
   * 例如:我想点击“表情”按钮显示“表情面板”,我就可以这样做:<br/>
   * viewbinder viewbinder = new viewbinder(btn_emotion,emotionpanel);<br/>
   * 这样就创建出了一个viewbinder对象<br/>
   * <font color='red'>【注意事项,使用此类时,千万不要使用trigger的setonclicklistener来监听事件(
   * 使用ontriggerclicklistener来代替),也不要使用settag来设置tag,否则会导致使用异常】</font>
   * 
   * @author 李长军
   * 
   */
  public static class viewbinder {
    private view trigger;
    private view panel;
    private ontriggerclicklistener listener;

    /**
     * 创建viewbinder对象<br/>
     * 例如:我想点击“表情”按钮显示“表情面板”,我就可以这样做:<br/>
     * viewbinder viewbinder = new
     * viewbinder(btn_emotion,emotionpanel,listener);<br/>
     * 这样就创建出了一个viewbinder对象
     * 
     * @param trigger
     *      触发对象
     * @param panel
     *      点击触发对象需要显示/隐藏的面板对象
     * @param listener
     *      trigger点击的监听器(千万不要使用setonclicklistener,否则会覆盖本工具类的监听器)
     */
    public viewbinder(view trigger, view panel,
        ontriggerclicklistener listener) {
      this.trigger = trigger;
      this.panel = panel;
      this.listener = listener;
      trigger.setclickable(true);
    }

    @override
    public boolean equals(object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (getclass() != obj.getclass())
        return false;
      viewbinder other = (viewbinder) obj;
      if (panel == null) {
        if (other.panel != null)
          return false;
      } else if (!panel.equals(other.panel))
        return false;
      if (trigger == null) {
        if (other.trigger != null)
          return false;
      } else if (!trigger.equals(other.trigger))
        return false;
      return true;
    }

    public ontriggerclicklistener getlistener() {
      return listener;
    }

    public void setlistener(ontriggerclicklistener listener) {
      this.listener = listener;
    }

    public view gettrigger() {
      return trigger;
    }

    public void settrigger(view trigger) {
      this.trigger = trigger;
    }

    public view getpanel() {
      return panel;
    }

    public void setpanel(view panel) {
      this.panel = panel;
    }

  }

  /**
   * 点击软键盘区域以外自动关闭软键盘的遮罩view
   * 
   * @author 李长军
   */
  private class closekeyboardonoutsidecontainer extends framelayout {

    public closekeyboardonoutsidecontainer(context context) {
      this(context, null);
    }

    public closekeyboardonoutsidecontainer(context context,
        attributeset attrs) {
      this(context, attrs, 0);
    }

    public closekeyboardonoutsidecontainer(context context,
        attributeset attrs, int defstyle) {
      super(context, attrs, defstyle);
    }

    @override
    public boolean dispatchtouchevent(motionevent event) {
      boolean iskeyboardshowing = iskeyboardshowing();
      boolean isemotionpanelshowing = haspanelshowing();
      if ((iskeyboardshowing || isemotionpanelshowing)
          && event.getaction() == motionevent.action_down) {
        int touchy = (int) (event.gety());
        int touchx = (int) (event.getx());
        if (istouchkeyboardoutside(touchy)) {
          if (iskeyboardshowing) {
            hidekeybordandsetflag(activity.getcurrentfocus());
          }
          if (isemotionpanelshowing) {
            closeallpanels();
          }
        }
        if (istouchedfoucusview(touchx, touchy)) {
          // 如果点击的是输入框,那么延时折叠表情面板
          postdelayed(new runnable() {
            @override
            public void run() {
              setkeyboardshowing(true);
            }
          }, 500);
        }
      }
      return super.ontouchevent(event);
    }
  }

  /**
   * 屏幕参数的辅助工具类。例如:获取屏幕高度,宽度,statusbar的高度,px和dp互相转换等
   * 【注意,使用之前一定要初始化!一次初始化就ok(建议app启动时进行初始化)。 初始化代码 displayutils.init(context)】
   * 
   * @author 李长军 2016.11.25
   */
  private static class displayutils {

    // 四舍五入的偏移值
    private static final float round_ceil = 0.5f;
    // 屏幕矩阵对象
    private static displaymetrics sdisplaymetrics;
    // 资源对象(用于获取屏幕矩阵)
    private static resources sresources;
    // statusbar的高度(由于这里获取statusbar的高度使用的反射,比较耗时,所以用变量记录)
    private static int statusbarheight = -1;

    /**
     * 初始化操作
     * 
     * @param context
     *      context上下文对象
     */
    public static void init(context context) {
      sdisplaymetrics = context.getresources().getdisplaymetrics();
      sresources = context.getresources();
    }

    /**
     * 获取屏幕高度 单位:像素
     * 
     * @return 屏幕高度
     */
    public static int getscreenheight() {
      return sdisplaymetrics.heightpixels;
    }

    /**
     * 获取屏幕宽度 单位:像素
     * 
     * @return 屏幕宽度
     */
    public static float getdensity() {
      return sdisplaymetrics.density;
    }

    /**
     * dp 转 px
     * 
     * @param dp
     *      dp值
     * @return 转换后的像素值
     */
    public static int dp2px(int dp) {
      return (int) (dp * getdensity() + round_ceil);
    }

    /**
     * 获取状态栏高度
     * 
     * @return 状态栏高度
     */
    public static int getstatusbarheight() {
      // 如果之前计算过,直接使用上次的计算结果
      if (statusbarheight == -1) {
        final int defaultheightindp = 19;// statusbar默认19dp的高度
        statusbarheight = displayutils.dp2px(defaultheightindp);
        try {
          class<?> c = class.forname("com.android.internal.r$dimen");
          object obj = c.newinstance();
          field field = c.getfield("status_bar_height");
          statusbarheight = sresources.getdimensionpixelsize(integer
              .parseint(field.get(obj).tostring()));
        } catch (exception e) {
          e.printstacktrace();
        }
      }
      return statusbarheight;
    }
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网