在android开发中控制软键盘是非常令人头疼的一件事,因为Android并没有开放出一个接口给开发者去简单易用的控制键盘的弹出与隐藏(这个时候就羡慕IOS的开发者们了。。。)。那假如说我有这么一个需求:我的界面中有一个输入框,我需要根据软键盘的状态来控制说,如果键盘弹出的话editText就显示为绿色,如果隐藏的话就显示为灰色。我怎么去控制它呢,今天想了一个简单的方法,试了也是可以的,不过有限制,但聊胜于无。发出来,有需要的可以带走。
思想就是重写onLayout方法,得到界面高度,这时候需要在AndroidManfest文件中设置activity 的 android:windowSoftInputMode="adjustResize" ,这样界面高度上才会有变化。
话不多说,上代码:
package com.example.testline;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class AnimView extends RelativeLayout {
private int tempBottom = 0;
private int bottom = 0;
private LayoutChangeListener listener;
private boolean isFirstRun = true;
public AnimView(Context context) {
super(context);
}
public AnimView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public AnimView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setListener(LayoutChangeListener listener) {
this.listener = listener;
}
public interface LayoutChangeListener {
void keyboardClose();
void keyboardOpen();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (isFirstRun) {
bottom = b;
}
if ((tempBottom - b) < 0) {
System.out.println("关闭");
listener.keyboardClose();
} else if ((tempBottom - b) > bottom / 3) {
System.out.println("展开");
listener.keyboardOpen();
}
isFirstRun = false;
tempBottom = b;
}
}
public class MainActivity extends Activity implements LayoutChangeListener {
private EditText et;
private AnimView av;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
av = (AnimView) findViewById(R.id.av);
av.setListener(this);
}
@Override
public void keyboardClose() {
et.setBackgroundResource(R.color.yellow);
}
@Override
public void keyboardOpen() {
et.setBackgroundResource(R.color.red);
}
}
<com.example.testline.AnimView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/av"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</com.example.testline.AnimView>
就这么简单,很好用,但是需要设置android:windowSoftInputMode="adjustResize" 。需要的可以带走。
作者原创,欢迎转载,转载请注明原地址