Android View :完美实现EditText 在软键盘上边

2017年8月28日 21:22:45 更新,下班回来重新翻起很久以前的项目代码,看了一下,写了个小demo,正常运行,看不明白这里代码的的可以直接下载demo 源码看一下,可能图片有些被拉伸。

链接: https://pan.baidu.com/s/1jJRuILw 密码: jupb
2018年2月5日 20:59:19 更新 (原来的百度抽风说我文件包含敏感信息,我也是醉了)

demo 只是简单的实现点击button 弹出 把编辑框文本内容更新到Textview上。

此方法基于PopupWindow,适合需要回复内容时响应点击事件,打开软键盘,编辑框在软键盘上部。
优点,编辑框使用CleanEdittext,监听输入状态来更改回复按钮颜色,添加title等。
先展示效果
点击评论打开软键盘,编辑框在软键盘上部,点击其他区域消失收起软键盘:


Paste_Image.png
Paste_Image.png

1.BaseSelectPopupWindow 的代码。

public class BaseSelectPopupWindow extends PopupWindow {

private View popView;

private View view;


private OnHeadClickListener onHeadClickListener;


private TextView tv_head;


protected Context context;


private boolean isOpenKeyboard=false;;


private boolean isShowTitle=true;

private boolean isOkClose=true;


protected int maxTextSize = 24;
protected int minTextSize = 14;
public BaseSelectPopupWindow(Context context, int layoutId  ) {

    this.context=context;
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    popView = inflater.inflate(R.layout.pop_view, null);
    tv_head=(TextView) popView.findViewById(R.id.tv_head);
    
    LinearLayout contentView = (LinearLayout) popView
            .findViewById(R.id.content);
    view=inflater.inflate(layoutId, null);
    contentView.addView(view,contentView.getLayoutParams());
    // btn_take_photo.setOnClickListener(itemsOnClick);
    // 设置SelectPicPopupWindow的View
    this.setContentView(popView);
    // 设置SelectPicPopupWindow弹出窗体的宽
    this.setWidth(LayoutParams.FILL_PARENT);
    // 设置SelectPicPopupWindow弹出窗体的高

    WindowManager wm = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
//  this.setHeight(wm.getDefaultDisplay().getHeight() / 2);
    this.setHeight(LayoutParams.WRAP_CONTENT);
    // 设置SelectPicPopupWindow弹出窗体可点击
    this.setFocusable(true);
    // 设置SelectPicPopupWindow弹出窗体动画效果
    this.setAnimationStyle(R.style.AnimBottom);
    // 实例化一个ColorDrawable颜色为半透明
    ColorDrawable dw = new ColorDrawable(0xb0000000);
    // 设置SelectPicPopupWindow弹出窗体的背景
    this.setBackgroundDrawable(dw);
    // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框

    /*
     * popView.setOnTouchListener(new OnTouchListener() {
     * 
     * public boolean onTouch(View v, MotionEvent event) {
     * 
     * int height = popView.findViewById(R.id.pop_layout).getTop(); int
     * y=(int) event.getY(); if(event.getAction()==MotionEvent.ACTION_UP){
     * if(y<height){ dismiss(); } } return true; } });
     */

    (popView.findViewById(R.id.btn_back)).setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View v) {
             dismiss();
        }
    });

    (popView.findViewById(R.id.btn_right)).setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            if(onHeadClickListener!=null){
                onHeadClickListener.okListener();
            }
            if(isOkClose){
                dismiss();
            }
            
        }
    });
    
    if(isOpenKeyboard){
        openKeyboard();
    }
    
    

}
public boolean isShowTitle() {
    return isShowTitle;
}
public void setShowTitle(boolean isShowTitle) {
    this.isShowTitle = isShowTitle;
    if(!isShowTitle){
        ((RelativeLayout)tv_head.getParent()).setVisibility(View.GONE);
    }
}
/**
 * 打开软键盘
 */
private  void openKeyboard() {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                @Override
                public void run() {
                        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                }
        }, 1000);
}
public boolean isOpenKeyboard() {
    return isOpenKeyboard;
}
public void setOpenKeyboard(boolean isOpenKeyboard) {
    this.isOpenKeyboard = isOpenKeyboard;
}

public OnHeadClickListener getOnHeadClickListener() {
    return onHeadClickListener;
}

public void setOnHeadClickListener(OnHeadClickListener onHeadClickListener) {
    this.onHeadClickListener = onHeadClickListener;
}

public interface OnHeadClickListener{
    public void okListener();
}



public void setTitle(String value){
    if(tv_head!=null){
        tv_head.setText(value);
    }
}
public boolean isOkClose() {
    return isOkClose;
}
public void setOkClose(boolean isOkClose) {
    this.isOkClose = isOkClose;
}
public Context getContext() {
    return context;
}

对应的XML 布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white_gray"
android:gravity="center_vertical" >

<RelativeLayout
    android:id="@+id/head"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:layout_alignParentTop="true"
    android:background="@color/head_yellow" >

    <TextView
        android:id="@+id/btn_back"
        style="@style/nav_side_title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:text="@string/cancel"
        android:textColor="@color/black_light_color"
        android:textSize="@dimen/TitleTextSize" />

    <TextView
        android:id="@+id/tv_head"
        style="@style/nav_head_title_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:ellipsize="end"
        android:gravity="center"
        android:visibility="gone" />

    <TextView
        android:id="@+id/btn_right"
        style="@style/nav_side_title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="15dp"
        android:text="@string/sure"
        android:textColor="@color/black"
        android:textSize="@dimen/TitleTextSize" />
</RelativeLayout>

<LinearLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/head"
    android:gravity="center"
    android:orientation="vertical" >
  </LinearLayout>

</RelativeLayout>

其中style:nav_side_title_text是定义文字大小的。
2.需要使用的时候

  private BaseSelectPopupWindow popWiw;// 回复的 编辑框 

声明之后使用的时候初始化并调用:

 private void popWiw( ) {

    popWiw = new BaseSelectPopupWindow(context, R.layout.edit_data);
    // popWiw.setOpenKeyboard(true);
    popWiw.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
    popWiw.setFocusable(true);
    popWiw.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    popWiw.setShowTitle(false);
    InputMethodManager im = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    im.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    final Button send = (Button) popWiw.getContentView().findViewById(
            R.id.btn_send);
    final EditText edt = (EditText) popWiw.getContentView().findViewById(
            R.id.edt_content);
  
    edt.setInputType(EditorInfo.TYPE_CLASS_TEXT);
    edt.setImeOptions(EditorInfo.IME_ACTION_SEND);
    edt.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            if (TextUtils.isEmpty(edt.getText())) {
                send.setEnabled(false);
            } else {
                send.setEnabled(true);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    edt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId,
                                      KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND
                    || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {

                if (!TextUtils.isEmpty(edt.getText().toString().trim())) {
            String content = edt.getText().toString().trim();
                   // /提交内容   sumbit(content)
                    popWiw.dismiss();
                }
                return true;
            }
            return false;
        }
    });
    send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!TextUtils.isEmpty(edt.getText().toString().trim())) {

                // /提交内容
                String content = edt.getText().toString().trim();
               
                popWiw.dismiss();
            }
        }
    });

    popWiw.setTitle("回复" + nickname);
    popWiw.showAtLocation(refreshLayout, Gravity.BOTTOM
            | Gravity.CENTER_HORIZONTAL, 0, 0);
}

对应的edit_data xml布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dp" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@drawable/bg_search"
    android:gravity="clip_vertical"
    android:orientation="vertical"
    android:paddingLeft="12dp"
    android:paddingRight="12dp" >

    <com.myapp.view.ClearEditText
        android:id="@+id/edt_content"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="65dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/edittext_back"
        android:focusable="true"
        android:hint="说点什么..."
        android:paddingLeft="10dp"
        android:imeOptions="actionSend"
        android:paddingRight="10dp"
        android:textColor="@color/top_bg_shadow"
        android:textSize="@dimen/NormalTextSize" >
    </com.myapp.view.ClearEditText>

    <Button
        android:id="@+id/btn_send"
        android:layout_width="60dp"
        android:layout_height="34dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:background="@drawable/btn_send_rounded"
        android:enabled="false"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:text="@string/send"
        android:textColor="@color/white"
        android:textSize="@dimen/NormalTextSize" />
</RelativeLayout>

</LinearLayout>

对于ClearEditText,应该都不陌生,

public class ClearEditText extends EditText implements  
    OnFocusChangeListener, TextWatcher { 
/**
 * 删除按钮的引用
 */
private Drawable mClearDrawable; 

public ClearEditText(Context context) { 
    this(context, null); 
} 

public ClearEditText(Context context, AttributeSet attrs) { 
    //这里构造方法也很重要,不加这个很多属性不能再XML里面定义
    this(context, attrs, android.R.attr.editTextStyle); 
} 

public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}


private void init() { 
    //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
    mClearDrawable = getCompoundDrawables()[2]; 
    if (mClearDrawable == null) { 
        mClearDrawable = getResources() 
                .getDrawable(R.drawable.icon_edit_del); 
    } 
    mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); 
    setClearIconVisible(false); 
    setOnFocusChangeListener(this); 
    addTextChangedListener(this); 
} 

/**
 * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件
 * 当我们按下的位置 在  EditText的宽度 - 图标到控件右边的间距 - 图标的宽度  和
 * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向没有考虑
 */
@Override 
public boolean onTouchEvent(MotionEvent event) { 
    if (getCompoundDrawables()[2] != null) { 
        if (event.getAction() == MotionEvent.ACTION_UP) { 
            boolean touchable = event.getX() > (getWidth() 
                    - getPaddingRight() - mClearDrawable.getIntrinsicWidth()) 
                    && (event.getX() < ((getWidth() - getPaddingRight())));
            if (touchable) { 
                this.setText(""); 
            } 
        } 
    } 

    return super.onTouchEvent(event); 
} 

/**
 * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
 */
@Override 
public void onFocusChange(View v, boolean hasFocus) { 
    if (hasFocus) { 
        setClearIconVisible(getText().length() > 0); 
    } else { 
        setClearIconVisible(false); 
    } 
} 


/**
 * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
 * @param visible
 */
protected void setClearIconVisible(boolean visible) { 
    Drawable right = visible ? mClearDrawable : null; 
    setCompoundDrawables(getCompoundDrawables()[0], 
            getCompoundDrawables()[1], right, getCompoundDrawables()[3]); 
} 
 

/**
 * 当输入框里面内容发生变化的时候回调的方法
 */
@Override 
public void onTextChanged(CharSequence s, int start, int count, 
        int after) { 
    setClearIconVisible(s.length() > 0); 
} 

@Override 
public void beforeTextChanged(CharSequence s, int start, int count, 
        int after) { 
     
} 

@Override 
public void afterTextChanged(Editable s) { 
     
} 


/**
 * 设置晃动动画
 */
public void setShakeAnimation(){
    this.setAnimation(shakeAnimation(5));
}


/**
 * 晃动动画
 * @param counts 1秒钟晃动多少下
 * @return
 */
public static Animation shakeAnimation(int counts){
    Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
    translateAnimation.setInterpolator(new CycleInterpolator(counts));
    translateAnimation.setDuration(1000);
    return translateAnimation;
}
}

一些icon 及圆角背景就不展示了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,277评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,777评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,946评论 0 245
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,271评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,636评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,767评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,989评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,733评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,457评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,674评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,155评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,518评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,160评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,114评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,898评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,822评论 2 280
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,705评论 2 273

推荐阅读更多精彩内容