android:監聽軟件盤“返回”鍵顯示隱藏事件

這裏有2種處理方法,先看複雜的:

一、軟件盤彈出隱藏時在mainfest裏設置  android:windowSoftInputMode="adjustResize"會改變佈局的大小,即onSizeChanged()方法會被調用。

我們如果要在軟件盤隱藏時操作EditText裏的內容,比如軟件盤隱藏時使EditText失去焦點,可用如下2種方法。

方法一:

一、自定義佈局

package hyz.com;

import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout;

public class ResizeLayout extends RelativeLayout { private OnResizeListener mListener; public interface OnResizeListener { void OnResize(int w, int h, int oldw, int oldh); } public void setOnResizeListener(OnResizeListener l) { Log.i("ResizeLayout:setOnResizeListener"); mListener = l; } public ResizeLayout(Context context, AttributeSet attrs) { super(context, attrs); Log.i("ResizeLayout:ResizeLayout"); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); Log.i("ResizeLayout:onSizeChanged"); if (mListener != null) { mListener.OnResize(w, h, oldw, oldh); } } }
二、引用自定義佈局
<hyz.com.ResizeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/resizeLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    ......
</hyz.com.ResizeLayout>

三、在mainfest裏的Activity添加
android:windowSoftInputMode="adjustResize"                                                                                          如:                                                                                                                           <activity android:name=".MyTabActivity"            
                  android:screenOrientation="portrait"
                  android:windowSoftInputMode="adjustResize">
四、在Activity中設置該佈局的監聽事件
首先Acitivity實現自定義佈局裏面的OnResizeListener接口
然後設置監聽
layout = (ResizeLayout) findViewById(R.id.resizeLayout);
layout.setOnResizeListener(this); 
接着複寫方法
 @Override
 public void OnResize(int w, int h, int oldw, int oldh) 
 {
  Log.i(h+":"+oldh);
  if (h >= oldh) 
  {
   Log.i("CountdownActivity:OnResize()");
   handler.sendEmptyMessage(MSG_CLEAR);
  }  
 }
private Handler handler = new Handler() 
     {
      public void handleMessage(Message msg)       
      {
       switch (msg.what) 
       {
        case MSG_CLEAR:
        {
         clearFocus();            
         break;
        }
        default:
         break;
   }
   super.handleMessage(msg);
  }
 };
上面的原理是,軟件盤隱藏,導致佈局大小變化,接着調用監聽器,然後發送Message,最後在handler裏處理事件。
 
 
方法二:這個方法在4.0以上沒用,不過2.3可行,3.0的沒試過
 
由於軟件盤彈出,接着按返回鍵隱藏軟件盤。這個返回鍵監聽是被屏蔽了的,無法在onKeyDown()裏監聽返回鍵。
不過Acitivity裏有個方法dispatchKeyEvent()
@Override
 public boolean dispatchKeyEvent(KeyEvent event) 
 {
  Log.i("CountdownActivity:dispatchKeyEvent()");
  if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
  {
   clearFocus();
  }
  return super.dispatchKeyEvent(event);
 }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章