如果要从活动中处理imm(虚拟)键盘窗口的显示/隐藏,则需要对布局进行子类化并覆盖onMesure方法(以便确定布局的测量宽度和测量高度)。在此之后,通过setContentView()设置子类布局作为活动的主视图。现在,您将能够处理imm显示/隐藏窗口事件。如果这听起来很复杂的话,那也不是真的。下面是代码:
main.xml<?xml version="1.0" encoding="utf-8"?>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
android:id="@+id/SearchText"
android:text=""
android:inputType="text"
android:layout_width="fill_parent"
android:layout_height="34dip"
android:singleLine="True"
/>
android:id="@+id/Search"
android:layout_width="60dip"
android:layout_height="34dip"
android:gravity = "center"
/>
现在您的活动中为布局声明子类(main.xml)public class MainSearchLayout extends LinearLayout {
public MainSearchLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.main, this);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d("Search Layout", "Handling Keyboard Window shown");
final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
final int actualHeight = getHeight();
if (actualHeight > proposedheight){
// Keyboard is shown
} else {
// Keyboard is hidden
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}}
从代码中可以看到,我们在子类构造函数中为我们的活动膨胀了布局。inflater.inflate(R.layout.main, this);
现在只需为我们的活动设置子类布局的内容视图。public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainSearchLayout searchLayout = new MainSearchLayout(this, null);
setContentView(searchLayout);
}
// rest of the Activity code and subclassed layout...}