主要实现:Android软键盘手动显示、隐藏、布局上移和EditText上移
- AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo0831"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- 布局整体上移adjustPan|stateHidden -->
<!-- 单输入框上移整体adjustResize|stateHidden -->
<activity
android:name="com.example.demo0831.MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="adjustResize|stateHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- MainActivity.java
package com.example.demo0831;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Button bt_open_keyboard;
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setSoftInputMode(
// WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
bt_open_keyboard = (Button) findViewById(R.id.bt_open_keyboard);
et = (EditText) findViewById(R.id.et);
bt_open_keyboard.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 方法一(如果输入法在窗口上已经显示,则隐藏,反之则显示)
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
// 方法二(view为接受软键盘输入的视图,SHOW_FORCED表示强制显示)
// InputMethodManager imm = (InputMethodManager)
// getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(et, InputMethodManager.SHOW_FORCED);
// imm.hideSoftInputFromWindow(et.getWindowToken(), 0); //强制隐藏键盘
}
});
}
}
- activity_main.xml
<RelativeLayout 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=".MainActivity" >
<Button
android:id="@+id/bt_open_keyboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom" />
</RelativeLayout>