需求:打开界面,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;
@Override
protected 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() {
@Override
public void run() {
// 打开软键盘
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(et_username, 0);
}
}, 1000);
}
// 监听onTouchEvent事件,关闭软键盘。
// getWindow().getDecorView()的意思是获取window的最前面的view。软键盘是phonewindow的跟view
@Override
public 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}" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="20dp" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
android:text="登录名:" />
<EditText
android:id="@+id/et_username"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="20dp" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
android:text="用户密码:" />
<EditText
android:id="@+id/et_userpassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:inputType="textPassword" />
</LinearLayout>
</LinearLayout>
源码下载地址:点击打开链接
本文介绍如何在Android中实现EditView在打开界面时自动弹出软键盘,并在点击软键盘以外的区域时自动隐藏软键盘。通过布局设置和监听键盘状态来达到效果。

3516

被折叠的 条评论
为什么被折叠?



