Android聊天室输入框之仿微信加号按钮实现
功能一开始理顺起来感觉很复杂,要判断多种情况。所以首先先理清思路,然后再写(找)代码。
当点击加号时有两种情况: 1.输入框下方菜单开启时: 1.软键盘关闭,但输入框位置不变,露出下方菜单。 2.软键盘开启,但输入框位置不变,下方菜单被软键盘完全遮盖 2.输入框下方菜关闭时: 1.软键盘不动,输入框位置提到软键盘高度,露出下方菜单
经过分析首先需要实时获取的属性是软键盘的开闭状态,软键盘高度
软键盘的开闭状态获取还有开闭方法在网上很好找,这里粘贴了一份。软键盘的高度经过查找也有很多方式,实际试了两种
1.通过自定义布局重写onSizeChange()方法+adjust_resize属性(也是我实际用的方式)
2.通过globleLayoutListener监听Activity的根部局尺寸
思路理清,必要的条件也有了接下来就是代码实现。这里做了一些优化,把软键盘尺寸存到了SharedPreference里面
首先是界面的根部局:
package com.suikajy.jiimdemo2.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.suikajy.jiimdemo2.utils.LogUtils
/**
* 作为聊天室界面的最底层布局,仅仅是监听界面尺寸的改变
*
* @author zjy
* @date 2017/11/7
*/
class ReSizeLayout : LinearLayout {
private var mSizeChangeListener: OnSizeChangeListener? = null
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
LogUtils.e("onSizeChanged : new: $w $h old: $oldw,$oldh")
if (mSizeChangeListener != null) {
mSizeChangeListener!!.onSizeChanged(w, h, oldw, oldh)
}
}
fun setOnSizeChangeListener(listener: OnSizeChangeListener) {
mSizeChangeListener = listener
}
interface OnSizeChangeListener {
fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)
}
}
然后是获取软键盘状态的工具类:
package com.suikajy.jiimdemo2.utils
import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
/**
* @author zjy
* @date 2017/11/27
*/
/**
* 获取根部局高度
* @rootView 根布局
*/
public fun computeUsableHeight(rootView: View): Int {
val r = Rect()
rootView.getWindowVisibleDisplayFrame(r)
// 全屏模式下:直接返回r.bottom,r.top其实是状态栏的高度
return r.bottom - r.top
}
/**
* 打开软键盘
*
* @param mEditText
* @param mContext
*/
fun openKeyboard(mEditText: EditText, mContext: Context) {
val imm = mContext
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY)
}
/**
* 关闭软键盘
*
* @param mEditText 输入框
* @param mContext 上下文
*/
fun closeKeyboard(mEditText: EditText, mContext: Context) {
val imm = mContext
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(mEditText.windowToken, 0)
}
/**
* 判断当前软键盘是否打开
*
* @param activity
* @return
*/
fun isSoftInputShow(activity: Activity): Boolean {
// 虚拟键盘隐藏 判断view是否为空
val view = activity.window.peekDecorView()
if (view != null) {
// 隐藏虚拟键盘
val inputmanger = activity
.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
// inputmanger.hideSoftInputFromWindow(view.getWindowToken(),0);
return inputmanger.isActive && activity.window.currentFocus != null
}
return false
}
最后就是Activity和布局文件了,都很简单(其中activity中封装了SharedPreference的委托,后面也粘有委托方法,或者直接无视当成一个普通变量也没事,不影响主体):
package com.suikajy.jiimdemo2.module.custom_private_chat
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.WindowManager
import com.suikajy.jiimdemo2.R
import com.suikajy.jiimdemo2.common.App
import com.suikajy.jiimdemo2.common.preference
import com.suikajy.jiimdemo2.utils.DensityUtil
import com.suikajy.jiimdemo2.utils.closeKeyboard
import com.suikajy.jiimdemo2.utils.isSoftInputShow
import com.suikajy.jiimdemo2.utils.openKeyboard
import com.suikajy.jiimdemo2.widget.ReSizeLayout
import kotlinx.android.synthetic.main.activity_custom_private_chat.*
/**
*
* @author zjy
* @date 2017/11/24
*/
class CustomChatActivity : AppCompatActivity(), ReSizeLayout.OnSizeChangeListener {
/**
* 软键盘和菜单在展示时是互斥的,可以同时不展示
*/
private var isMenuShow = false
/**
* 软键盘高度,通过SharedPreference缓存,如果没有就使用默认的500dp作为高度
*/
private var keyboardHeight by preference(App.instance, "KEYBOARD_HEIGHT", DensityUtil.dip2px(App.instance, 500f))
private var mScreenHeight: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
setContentView(R.layout.activity_custom_private_chat)
val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
mScreenHeight = wm.defaultDisplay.height
rsl.setOnSizeChangeListener(this)
initClick()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
if (h.toFloat() / mScreenHeight < 0.8f) {
keyboardHeight = oldh - h
}
//设置EditText跟随
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
if (isSoftInputShow(this) && !isMenuShow) {
fl_menu.layoutParams.height = 0
fl_menu.requestLayout()
}
}
private fun initClick() {
btn_plus.setOnClickListener({
if (isMenuShow) {
//菜单打开状态下,继续点击弹出输入框
isMenuShow = false
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
openKeyboard(etInput, this@CustomChatActivity)
} else {
isMenuShow = true
//解除EditText跟随
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
if (isSoftInputShow(this)) {
//菜单未展示,输入框打开状态下,打开菜单
closeKeyboard(etInput, this@CustomChatActivity)
fl_menu.layoutParams.height = keyboardHeight
fl_menu.requestLayout()
} else {
//菜单未展示,输入框关闭状态下,打开菜单
fl_menu.layoutParams.height = keyboardHeight
fl_menu.requestLayout()
}
}
})
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<com.suikajy.jiimdemo2.widget.ReSizeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rsl"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_msg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_above="@+id/layout_input"
android:layout_weight="1" />
<LinearLayout
android:id="@+id/layout_input"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:background="#f0f0f0"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/etInput"
android:hint="请输入文字" />
<Button
android:id="@+id/mBtnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit" />
<Button
android:id="@+id/btn_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/fl_menu"
android:background="#ddd"/>
</com.suikajy.jiimdemo2.widget.ReSizeLayout>
委托方法:
/**
* SharedPreference委托
*/
fun <T : Any> preference(context: Context, key: String, default: T): ReadWriteProperty<Any?, T> = Preference(context, key, default)
private class Preference<T>(val context: Context, val key: String, val default: T) : ReadWriteProperty<Any?, T> {
val preferences: SharedPreferences by lazy {
context.getSharedPreferences("default_shared_preference", Context.MODE_PRIVATE)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return findPreference(key, default)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(key, value)
}
@Suppress("UNCHECKED_CAST")
private fun <T> findPreference(name: String, default: T): T = with(preferences) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type can not be saved into Preferences")
}
res as T
}
@SuppressLint("CommitPrefEdits")
private fun <U> putPreference(name: String, value: U) = with(preferences.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}.apply()
}
}