2018年9月18日 星期二

Android 開發筆記 - MenuItemCompat.getActionProvider return null

週末練練 Android 手感,試試 Cast SDK ,結果連最簡單的 CastButton 都弄不出來,一直碰到:

java.lang.IllegalArgumentException: menu item with ID ###### doesn't have a MediaRouteActionProvider.

跑去看了一下 CastButtonFactory.setUpMediaRouteButton 程式碼:

    public static MenuItem setUpMediaRouteButton(Context context, Menu menu, int i) {
        zzac.zzdn("Must be called from the main thread.");
        zzac.zzw(menu);
        CastContext sharedInstance = CastContext.getSharedInstance(context);
        MenuItem findItem = menu.findItem(i);
        if (findItem == null) {
            throw new IllegalArgumentException(String.format(Locale.ROOT, "menu doesn't contain a menu item whose ID is %d.", new Object[]{Integer.valueOf(i)}));
        }
        MediaRouteActionProvider mediaRouteActionProvider = (MediaRouteActionProvider) MenuItemCompat.getActionProvider(findItem);
        if (mediaRouteActionProvider == null) {
            throw new IllegalArgumentException(String.format(Locale.ROOT, "menu item with ID %d doesn't have a MediaRouteActionProvider.", new Object[]{Integer.valueOf(i)}));
        }
        mediaRouteActionProvider.setRouteSelector(sharedInstance.getMergedSelector());
        return findItem;
    }


才確認應該有什麼搞錯了,再追了一下,果真是 menu 的 xml 描述有問題,不小心把 app namespace 弄錯了,錯誤:

xmlns:app="http://schemas.android.com/tools"

正確:

xmlns:app="http://schemas.android.com/apk/res-auto"

就這樣耍廢了兩三個小時。

程式範例也才幾句話:

    @Override public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.navigation, menu);
        CastButtonFactory.setUpMediaRouteButton(getApplicationContext(),
                menu,
                R.id.media_route_menu_item);
        return true;
    }


為了 debug :

    @Override public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        getMenuInflater().inflate(R.menu.navigation, menu);

        MenuItem mMenuItem = menu.findItem(R.id.media_route_menu_item);
        if (mMenuItem != null) {
            Log.v("onCreateOptionsMenu", "Found");
            MediaRouteActionProvider mediaRouteActionProvider =
                    (MediaRouteActionProvider) MenuItemCompat.getActionProvider(mMenuItem);

            if (mediaRouteActionProvider != null) {
                Log.v("MediaRouteActionProvider", "Found");
            } else {
                Log.v("MediaRouteActionProvider", "Not Found");
            }
        } else {
            Log.v("onCreateOptionsMenu", "Not Found");
        }
        return true;

沒有留言:

張貼留言