分發事件給註冊了自定義介面的Fragment
阿新 • • 發佈:2018-12-07
需要實現點選fragment空白的地方來實現隱藏軟鍵盤,首先在其所依附的activity中重寫dispatchTouchEvent方法,並提供介面
//點選空白處,隱藏軟鍵盤 回撥介面
public interface MyTouchListener {
public void onTouchEvent(MotionEvent event);
}
/*
* 儲存MyTouchListener介面的列表
*/
private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<DDLiveBackgroundActivity.MyTouchListener>();
/**
* 提供給Fragment通過getActivity()方法來註冊自己的觸控事件的方法
*
* @param listener
*/
public void registerMyTouchListener(MyTouchListener listener) {
myTouchListeners.add(listener);
}
/**
* 提供給Fragment通過getActivity()方法來取消註冊自己的觸控事件的方法
*
* @param listener
*/
public void unRegisterMyTouchListener(MyTouchListener listener) {
myTouchListeners.remove(listener);
}
/**
* 分發觸控事件給所有註冊了MyTouchListener的介面
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean dispatch = super.dispatchTouchEvent(ev);
for (MyTouchListener listener : myTouchListeners) {
listener.onTouchEvent(ev);
}
return dispatch;
}
在fragment的onResume方法中註冊
DDLiveBackgroundActivity.MyTouchListener myTouchLinster = new DDLiveBackgroundActivity.MyTouchListener() {
@Override
public void onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (ETSettingH323Fragment.this.getActivity().getCurrentFocus() != null && ETSettingH323Fragment
.this.getActivity().getCurrentFocus().getWindowToken() != null) {
InputMethodManager manager = (InputMethodManager) ETSettingH323Fragment.this.getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(ETSettingH323Fragment.this.getActivity().getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
};
((DDLiveBackgroundActivity) this.getActivity()).registerMyTouchListener(myTouchLinster);
記得在fragment的onPause方法中取消註冊
if (myTouchLinster != null) {
((DDLiveBackgroundActivity) this.getActivity()).unRegisterMyTouchListener(myTouchLinster);
myTouchLinster = null;
}