android 虚拟键 隐藏事件,如何在Android中捕获“虚拟键盘显示/隐藏”事件?

如果要从活动中处理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...}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值