在MainActivity中写接口:
/**
* 便于fragment中实现dispatchKeyEvent
*/
public interface FragmentKeyeventListener
{
boolean onFragmentKeyEvent(KeyEvent event);
}
public void setFragmentKeyeventListener (FragmentKeyeventListener fragmentKeyeventListener) {
this.fragmentKeyeventListener = fragmentKeyeventListener;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
if (fragmentKeyeventListener != null)
{
if(fragmentKeyeventListener.onFragmentKeyEvent(event))
{
return true;
}
}
}
Fragment实现接口:
public class KeyPadFragment extends Fragment implements MainActivity.FragmentKeyeventListener
{
/**
* 设置按键动作显示效果
*
* @param event
* @return
*/
@Override
public boolean onFragmentKeyEvent(KeyEvent event)
{
}
}
因为Fragment只是View,操作都是基于Activity,该Fragment是进行按键处理,在点击返回键的时候产生了冲突,导致奔溃,便单独对返回键做了处理:
在Fragment类中做不生效:
@Override
public boolean onFragmentKeyEvent(KeyEvent event)
{
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (action)
{
case KeyEvent.ACTION_UP:
if (keyCode == KeyEvent.KEYCODE_BACK)
{
return false;
}
return true;
}
}
在Activity中做退出键处理:
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_BACK)
{
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Will exit this Application?");
dialogBuilder.setCancelable(false);
dialogBuilder.setPositiveButton("Yes", (dialog,which)->
{
finish();
});
dialogBuilder.setNegativeButton("No", (dialog,which)->{ });
dialogBuilder.show();
}
再提一点不相关的,但是让我后来长了点心眼儿的-----测试阶段,系统键盘映射值不对的时候,异常报错数组下标越界,导致程序崩溃,因此在fragment的按键处做了异常抛出:
case KeyEvent.ACTION_DOWN:
{
tv_KeyValue.setText("key-Down value: " + keyCode);
if (keyCode != 0 && keyCode != KeyEvent.KEYCODE_BACK)
{
try {
mkActivity.findViewById(keys[keyCode])
.setBackgroundResource(R.drawable.btn_select);
}
catch (ArrayIndexOutOfBoundsException|NullPointerException e)
{
Toast.makeText(getActivity(),getString(R.string.errorkey),Toast.LENGTH_SHORT)
.show();
}
}
}
return true;
关于键盘处理这一块改了很久,因为后来多个fragment的按键冲突,所以前期的设想很重要!