使用更为流行的 Kotlin 和 Material Design,可以通过使用TextInputEditText来实现(这种方法也适用于EditTextView)...
1. 使父视图(你的活动/片段的内容视图)可点击和可聚焦,通过添加以下属性:
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
2.为所有视图创建一个扩展(例如在ViewExtension.kt文件中):
fun View.hideKeyboard(){
val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(this.windowToken, 0)
}
3.创建一个继承TextInputEditText的BaseTextInputEditText。实现onFocusChanged方法,使当视图失去焦点时隐藏键盘:
class BaseTextInputEditText(context: Context?, attrs: AttributeSet?) : TextInputEditText(context, attrs){
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
if (!focused) this.hideKeyboard()
}
}
4.只需在XML中调用您全新的自定义视图:
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout"
...>
<com.your_package.BaseTextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
... />
</android.support.design.widget.TextInputLayout>
就这样。 无需修改您的控制器(片段或活动)来处理这种重复情况。
getFields()
的解决方案:https://dev59.com/e2sz5IYBdhLWcg3wlY-9 - Reto