TextInputLayout實(shí)現(xiàn)知乎輸入框效果 及 點(diǎn)擊空白處收起軟鍵盤
EditText中設(shè)置hint屬性來提示用戶輸入內(nèi)容株茶,在光標(biāo)未聚焦之前hint內(nèi)容正常顯示,當(dāng)光標(biāo)聚焦在當(dāng)前EditText時(shí)巷帝,hint的內(nèi)容通過動(dòng)畫過渡到輸入框的上方忌卤,給使用者帶來很舒服的使用體驗(yàn)。

效果圖
一.TextInputLayout效果實(shí)現(xiàn)
1.0 依賴庫appcompat-v7和Design Support Library
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
1.1添加布局
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/input_content"/>
</android.support.design.widget.TextInputLayout>
需要注意的是:TextInputLayout繼承于Linearlayout楞泼,它只能有一個(gè)子控件驰徊,且子控件只能是EditText。
1.2修改顏色
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="colorAccent">@color/colorAccent</item>
</style>
TextInputLayout內(nèi)的EditText字體顏色及下劃線的顏色由colorAccent決定堕阔,要想改變它們的顏色修改colorAccent的值即可棍厂。
二.點(diǎn)擊輸入框時(shí)軟鍵盤彈出,點(diǎn)擊空白處光標(biāo)失去焦點(diǎn)且軟鍵盤收起
【1】將目標(biāo)EditText的父控件(不是上文的TextInputLayout)超陆,設(shè)置為-->
android:focusable="true"
android:focusableInTouchMode="true"
【2】調(diào)用setOnTouchListener方法牺弹,當(dāng)點(diǎn)擊這個(gè)控件時(shí)當(dāng)前控件獲得焦點(diǎn)浦马,且強(qiáng)制關(guān)閉軟鍵盤。
CooldinatorLayout_Operate.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
CooldinatorLayout_Operate.setFocusable(true);
CooldinatorLayout_Operate.setFocusableInTouchMode(true);
CooldinatorLayout_Operate.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(CooldinatorLayout_Operate.getWindowToken(), 0);
return false;
}
});
其中张漂,
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(CooldinatorLayout_Operate.getWindowToken(), 0);
是強(qiáng)制關(guān)閉軟鍵盤的方法