editview软键盘弹出和隐藏
生活随笔
收集整理的這篇文章主要介紹了
editview软键盘弹出和隐藏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:打開界面,editview自動彈出。點擊軟鍵盤其它區域,則收起軟鍵盤。
先上圖:界面效果圖如下:
比較簡單:直接上代碼:
package com.testedittextdemo;import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.inputmethod.InputMethodManager; import android.widget.EditText;public class MainActivity extends Activity {EditText et_username;EditText et_password;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et_username = (EditText) findViewById(R.id.et_username);et_password = (EditText) findViewById(R.id.et_userpassword);//延時1s,的目的是等待view加載完成后,才能夠彈出軟鍵盤。否則,軟鍵盤可能彈出失敗。new Handler().postDelayed(new Runnable() {@Overridepublic void run() { // 打開軟鍵盤InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);manager.showSoftInput(et_username, 0);}}, 1000);}// 監聽onTouchEvent事件,關閉軟鍵盤。 // getWindow().getDecorView()的意思是獲取window的最前面的view。軟鍵盤是phonewindow的跟view@Overridepublic boolean onTouchEvent(MotionEvent event) { // 關閉軟鍵盤InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);manager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);return super.onTouchEvent(event);}}xml的文件布局為:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="${relativePackage}.${activityClass}" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:paddingLeft="20dp" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_gravity="bottom"android:layout_weight="1"android:text="登錄名:" /><EditTextandroid:id="@+id/et_username"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="3" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:paddingLeft="20dp" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_gravity="bottom"android:layout_weight="1"android:text="用戶密碼:" /><EditTextandroid:id="@+id/et_userpassword"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="3"android:inputType="textPassword" /></LinearLayout></LinearLayout>源碼下載地址:點擊打開鏈接
總結
以上是生活随笔為你收集整理的editview软键盘弹出和隐藏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 408笔记1
- 下一篇: 上月最新面过美团大众点评拿到offer的