Android项目里集成Cordova详解(6)

4.在自定义插件类里给步骤3里的mCordovaPlugin赋值

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { // TODO Auto-generated method stub mCallbackContext = callbackContext; /*给fragment所在activity里的mCordovaPlugin赋值,否则fragment所在activity里onActivityResult() * 无法将结果传给插件的onActivityResult()。*/ MyFragmentActivity.mCordovaPlugin = (CordovaPlugin) this; // 语音识别 if ("getSpeechData".equals(action)) { RequestData = args.getJSONObject(0); Intent intent = new Intent(cordova.getActivity(), SpeechActivity.class); intent.putExtra("flag", RequestData.getInt("flag")); this.cordova.startActivityForResult((CordovaPlugin) this, intent, CORDOVA_SPEEN); return true; } 十 Fragment拦截返回键

1.原理:利用Fragment的生命周期,在Fragment显示时通知到Activity,并由Activity保持。当用户按下物理返回键时,首先将back键请求交给Fragment处理,如果处理返回true,未处理时返回false。如果Fragment没有处理则由Activity处理。为保证Fragment存在嵌套的情况下也能正常使用,可以使用FragmentManager去管理持有的子Fragment,FragmentManager使用递归方式处理。

2.定义FragmentBackHandler接口

public interface FragmentBackHandler { //用于判断子fragment是否对返回键做处理 boolean onGoBack(); }

3.定义一个BackHandlerHelper工具类,用于实现分发back事件,Fragment和Activity的外理逻辑是一样,所以两者都需要调用该类的方法。

public class BackHandlerHelper { /** * 将back事件分发给 FragmentManager 中管理的子Fragment,如果该 FragmentManager * 中的所有Fragment都 没有处理back事件,则尝试 FragmentManager.popBackStack() * * @param fragmentManager * @return */ public static boolean handleBackPress(FragmentManager fragmentManager) { List<Fragment> fragments = fragmentManager.getFragments(); if (fragments == null) return false; for (int i = fragments.size() - 1; i >= 0; i--) { Fragment child = fragments.get(i); if (isFragmentBackHandled(child)) { return true; } } if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); return true; } return false; } public static boolean handleBackPress(Fragment fragment) { return handleBackPress(fragment.getChildFragmentManager()); } public static boolean handleBackPress(FragmentActivity fragmentActivity) { return handleBackPress(fragmentActivity.getSupportFragmentManager()); } public static boolean isFragmentBackHandled(Fragment fragment) { return fragment != null && fragment.isVisible() && fragment.getUserVisibleHint() // for ViewPager && fragment instanceof FragmentBackHandler && ((FragmentBackHandler) fragment).onGoBack(); } }

3.在Fragment里实现FragmentBackHandler接口

public class MyFragmentNew extends BaseFragment implements FragmentBackHandler{ @Override public boolean onGoBack() { if(myCordovaWebView.canGoBack()){ myCordovaWebView.getEngine().goBack(); return true; } //return BackHandlerHelper.handleBackPress(this); //当确认没有子Fragmnt时可以直接return false return false; } }

4.在宿主Activity覆盖onBackPressed方法

public class MyActivity extends FragmentActivity { //..... @Override public void onBackPressed() { //子Fragment没有做拦截处理 if (!BackHandlerHelper.handleBackPress(this)) { super.onBackPressed(); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f0f8ae4e81dfdaab8f001d6325e1e1d9.html