神奇的Android KeyEvent事件

最近项目中用到各种KeyEvent事件,之前各种问题,自己都解决了,今天发现两个奇葩问题。。。。

在onkeydow和onkeyup事件中我都实现了自己的方法,左右键requestfoucse后分别用dispatchKeyEvent根据Flag传给对应的view,那么问题就来了。。。

有三个view 1为gridview 2和3都为Gallery,当焦点在二或三的时候,按左或右,先要把gridview 的item走到头才能走gallery的item,而且此时gallery是有焦点的,而且也dispatchKeyEvent了。问题就是这样,后来了解到因为我专过来的event是我activity dispatchKeyEvent的。。。。而自己new一个就没问题,再有gridview 只需响应action_up事件,如果down和up都响应了那么会移动两次



/**
	 * 按左右时事件传给特定的控件,防止选中某项按左右时移动其他控件的问题
	 * ***/
	private void KEY_LEFT_OR_RIGHT(KeyEvent event) {
		switch (POSTION) {
		case GAMETYPE:
			if (!mGameTypeGridView.hasFocus()) {
				mGameTypeGridView.requestFocus();
			} 
			if (event.getAction()==KeyEvent.ACTION_DOWN) {
				return;
			}
			//Gridview 只需响应ACTION_UP,如DOWN和UP都响应会移动两次
//			mGameTypeGridView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, event.getKeyCode()));
			mGameTypeGridView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, event.getKeyCode()));
			POSTION=GAMETYPE;
			break;
		case RECOMMEND:
			if (!mRecommendGallery.hasFocus()) {
				mRecommendGallery.requestFocus();
			}
			
			if (mGameTypeGridviewLastSelectPostion!=0||mGameTypeGridviewLastSelectPostion!=mTopAdapter.getCount()-1) {
				if (event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT) {
					mGameTypeGridView.setSelection(0);
				}else {
					mGameTypeGridView.setSelection(mTopAdapter.getCount()-1);
				}
			}
			if (event.getAction()==KeyEvent.ACTION_DOWN) {
				return;
			}
			mRecommendGallery.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, event.getKeyCode()));
			mRecommendGallery.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, event.getKeyCode()));
			POSTION=RECOMMEND;
			break;
		case PLAYED:
			if (!mHistoryGallery.hasFocus()) {
				mHistoryGallery.requestFocus();
			}
			if (mGameTypeGridviewLastSelectPostion!=0||mGameTypeGridviewLastSelectPostion!=mTopAdapter.getCount()-1) {
				if (event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT) {
					mGameTypeGridView.setSelection(0);
				}else {
					mGameTypeGridView.setSelection(mTopAdapter.getCount()-1);
				}
			}
			if (event.getAction()==KeyEvent.ACTION_DOWN) {
				return;
			}
			mHistoryGallery.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, event.getKeyCode()));
			mHistoryGallery.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, event.getKeyCode()));
			POSTION=PLAYED;
			break;
		case USERINFO:
			//防止焦点在个人中心中最左边的位置再按左焦点会到游戏类型上
			if (!mPager.hasFocus()) {
				mPager.requestFocus();
			}
			break;
		default:
			break;
		}
	}


你可能感兴趣的:(神奇的Android KeyEvent事件)