Example usage for android.view ContextMenu add

List of usage examples for android.view ContextMenu add

Introduction

In this page you can find the example usage for android.view ContextMenu add.

Prototype

public MenuItem add(int groupId, int itemId, int order, CharSequence title);

Source Link

Document

Add a new item to the menu.

Usage

From source file:com.nttec.everychan.ui.NewTabFragment.java

private void openChansList() {
    final ArrayAdapter<ChanModule> chansAdapter = new ArrayAdapter<ChanModule>(activity, 0) {
        private LayoutInflater inflater = LayoutInflater.from(activity);
        private int drawablePadding = (int) (resources.getDisplayMetrics().density * 5 + 0.5f);

        {//from  w w  w  .ja  v a 2s.  co m
            for (ChanModule chan : MainApplication.getInstance().chanModulesList)
                add(chan);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ChanModule chan = getItem(position);
            TextView view = (TextView) (convertView == null
                    ? inflater.inflate(android.R.layout.simple_list_item_1, parent, false)
                    : convertView);
            view.setText(chan.getDisplayingName());
            view.setCompoundDrawablesWithIntrinsicBounds(chan.getChanFavicon(), null, null, null);
            view.setCompoundDrawablePadding(drawablePadding);
            return view;
        }
    };

    DialogInterface.OnClickListener onChanSelected = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ChanModule chan = chansAdapter.getItem(which);
            UrlPageModel model = new UrlPageModel();
            model.chanName = chan.getChanName();
            model.type = UrlPageModel.TYPE_INDEXPAGE;
            openNewTab(chan.buildUrl(model));
        }
    };

    final AlertDialog chansListDialog = new AlertDialog.Builder(activity)
            .setTitle(R.string.newtab_quickaccess_all_boards).setAdapter(chansAdapter, onChanSelected)
            .setNegativeButton(android.R.string.cancel, null).create();

    chansListDialog.getListView().setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            MenuItem.OnMenuItemClickListener contextMenuHandler = new MenuItem.OnMenuItemClickListener() {
                @SuppressLint("InlinedApi")
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    final ChanModule chan = chansAdapter
                            .getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
                    switch (item.getItemId()) {
                    case R.id.context_menu_favorites_from_fragment:
                        if (MainApplication.getInstance().database.isFavorite(chan.getChanName(), null, null,
                                null)) {
                            MainApplication.getInstance().database.removeFavorite(chan.getChanName(), null,
                                    null, null);
                        } else {
                            try {
                                UrlPageModel indexPage = new UrlPageModel();
                                indexPage.chanName = chan.getChanName();
                                indexPage.type = UrlPageModel.TYPE_INDEXPAGE;
                                MainApplication.getInstance().database.addFavorite(chan.getChanName(), null,
                                        null, null, chan.getChanName(), chan.buildUrl(indexPage));
                            } catch (Exception e) {
                                Logger.e(TAG, e);
                            }
                        }
                        return true;
                    case R.id.context_menu_quickaccess_add:
                        QuickAccess.Entry newEntry = new QuickAccess.Entry();
                        newEntry.chan = chan;
                        list.add(0, newEntry);
                        adapter.notifyDataSetChanged();
                        saveQuickAccessToPreferences();
                        chansListDialog.dismiss();
                        return true;
                    case R.id.context_menu_quickaccess_custom_board:
                        LinearLayout dialogLayout = new LinearLayout(activity);
                        dialogLayout.setOrientation(LinearLayout.VERTICAL);
                        final EditText boardField = new EditText(activity);
                        final EditText descriptionField = new EditText(activity);
                        boardField.setHint(R.string.newtab_quickaccess_addcustom_boardcode);
                        descriptionField.setHint(R.string.newtab_quickaccess_addcustom_boarddesc);
                        LinearLayout.LayoutParams fieldsParams = new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        dialogLayout.addView(boardField, fieldsParams);
                        dialogLayout.addView(descriptionField, fieldsParams);
                        DialogInterface.OnClickListener onOkClicked = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String boardName = boardField.getText().toString();
                                for (QuickAccess.Entry entry : list)
                                    if (entry.boardName != null && entry.chan != null)
                                        if (entry.chan.getChanName().equals(chan.getChanName())
                                                && entry.boardName.equals(boardName)) {
                                            Toast.makeText(activity,
                                                    R.string.newtab_quickaccess_addcustom_already_exists,
                                                    Toast.LENGTH_LONG).show();
                                            return;
                                        }

                                try {
                                    if (boardName.trim().length() == 0)
                                        throw new Exception();
                                    UrlPageModel boardPageModel = new UrlPageModel();
                                    boardPageModel.type = UrlPageModel.TYPE_BOARDPAGE;
                                    boardPageModel.chanName = chan.getChanName();
                                    boardPageModel.boardName = boardName;
                                    boardPageModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
                                    chan.buildUrl(boardPageModel); //,  ??  ?    
                                } catch (Exception e) {
                                    Toast.makeText(activity,
                                            R.string.newtab_quickaccess_addcustom_incorrect_code,
                                            Toast.LENGTH_LONG).show();
                                    return;
                                }

                                QuickAccess.Entry newEntry = new QuickAccess.Entry();
                                newEntry.chan = chan;
                                newEntry.boardName = boardName;
                                newEntry.boardDescription = descriptionField.getText().toString();
                                list.add(0, newEntry);
                                adapter.notifyDataSetChanged();
                                saveQuickAccessToPreferences();
                                chansListDialog.dismiss();
                            }
                        };
                        new AlertDialog.Builder(activity)
                                .setTitle(resources.getString(R.string.newtab_quickaccess_addcustom_title,
                                        chan.getChanName()))
                                .setView(dialogLayout).setPositiveButton(android.R.string.ok, onOkClicked)
                                .setNegativeButton(android.R.string.cancel, null).show();
                        return true;
                    }
                    return false;
                }
            };
            String thisChanName = chansAdapter.getItem(((AdapterView.AdapterContextMenuInfo) menuInfo).position)
                    .getChanName();
            boolean canAddToQuickAccess = true;
            for (QuickAccess.Entry entry : list)
                if (entry.boardName == null && entry.chan != null
                        && entry.chan.getChanName().equals(thisChanName)) {
                    canAddToQuickAccess = false;
                    break;
                }
            menu.add(Menu.NONE, R.id.context_menu_favorites_from_fragment, 1,
                    MainApplication.getInstance().database.isFavorite(thisChanName, null, null, null)
                            ? R.string.context_menu_remove_favorites
                            : R.string.context_menu_add_favorites)
                    .setOnMenuItemClickListener(contextMenuHandler);
            menu.add(Menu.NONE, R.id.context_menu_quickaccess_add, 2, R.string.context_menu_quickaccess_add)
                    .setOnMenuItemClickListener(contextMenuHandler).setVisible(canAddToQuickAccess);
            menu.add(Menu.NONE, R.id.context_menu_quickaccess_custom_board, 3,
                    R.string.context_menu_quickaccess_custom_board)
                    .setOnMenuItemClickListener(contextMenuHandler);
            if (isSingleboardChan(
                    chansAdapter.getItem(((AdapterView.AdapterContextMenuInfo) menuInfo).position)))
                menu.findItem(R.id.context_menu_quickaccess_custom_board).setVisible(false);
        }
    });
    chansListDialog.show();
}

From source file:com.github.dfa.diaspora_android.ui.ContextMenuWebView.java

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            HitTestResult result = getHitTestResult();
            String url = result.getExtra();
            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                boolean writeToStoragePermitted = true;
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    int hasWRITE_EXTERNAL_STORAGE = parentActivity
                            .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                        writeToStoragePermitted = false;
                        if (!parentActivity.shouldShowRequestPermissionRationale(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                    .setPositiveButton(context.getText(android.R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (android.os.Build.VERSION.SDK_INT >= 23)
                                                        parentActivity.requestPermissions(new String[] {
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                }
                                            })
                                    .setNegativeButton(context.getText(android.R.string.no), null).show();
                        }//from   w  w  w  . j  a  va 2s .co  m
                        parentActivity.requestPermissions(
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                    }
                }
                if (writeToStoragePermitted) {
                    if (url != null) {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        File destinationFile = new File(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
                        Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location)
                                + " " + destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    }
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {
                    boolean writeToStoragePermitted = true;
                    if (android.os.Build.VERSION.SDK_INT >= 23) {
                        int hasWRITE_EXTERNAL_STORAGE = parentActivity
                                .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                            writeToStoragePermitted = false;
                            if (!parentActivity.shouldShowRequestPermissionRationale(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                        .setPositiveButton(context.getText(android.R.string.yes),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        if (android.os.Build.VERSION.SDK_INT >= 23)
                                                            parentActivity.requestPermissions(new String[] {
                                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                    MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                    }
                                                })
                                        .setNegativeButton(context.getText(android.R.string.no), null).show();
                            } else {
                                parentActivity.requestPermissions(
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                            }
                        }
                    }
                    if (writeToStoragePermitted) {
                        final Uri local = Uri.parse(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        new ImageDownloadTask(null, local.getPath()) {
                            @Override
                            protected void onPostExecute(Bitmap result) {
                                Uri myUri = Uri.fromFile(new File(local.getPath()));
                                Intent sharingIntent = new Intent();
                                sharingIntent.setAction(Intent.ACTION_SEND);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
                                sharingIntent.setType("image/png");
                                sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                context.startActivity(Intent.createChooser(sharingIntent,
                                        getResources().getString(R.string.action_share_dotdotdot)));
                            }
                        }.execute(url);
                    }
                } else {
                    Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
                }

                break;

            case ID_IMAGE_EXTERNAL_BROWSER:
                if (url != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                }
                break;

            //Copy url to clipboard
            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) context
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            //Try to share link to other apps
            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    context.startActivity(Intent.createChooser(sendIntent,
                            getResources().getText(R.string.context_menu_share_link)));
                }
                break;
            }
            return true;
        }
    };

    //Build context menu
    if (result.getType() == HitTestResult.IMAGE_TYPE
            || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        // Menu options for an image.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0,
                context.getString(R.string.context_menu_open_external_browser))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == HitTestResult.ANCHOR_TYPE
            || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
        // Menu options for a hyperlink.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:com.github.dfa.diaspora_android.web.ContextMenuWebView.java

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            HitTestResult result = getHitTestResult();
            String url = result.getExtra();
            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                boolean writeToStoragePermitted = true;
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    int hasWRITE_EXTERNAL_STORAGE = parentActivity
                            .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                        writeToStoragePermitted = false;
                        if (!parentActivity.shouldShowRequestPermissionRationale(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                    .setPositiveButton(context.getText(android.R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (android.os.Build.VERSION.SDK_INT >= 23)
                                                        parentActivity.requestPermissions(new String[] {
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                }
                                            })
                                    .setNegativeButton(context.getText(android.R.string.no), null).show();
                        }/*from   ww  w  .ja  v a2  s  .c o m*/
                        parentActivity.requestPermissions(
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                    }
                }
                if (writeToStoragePermitted) {
                    if (url != null) {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        File destinationFile = new File(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);

                        Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location)
                                + " " + destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    }
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {
                    boolean writeToStoragePermitted = true;
                    if (android.os.Build.VERSION.SDK_INT >= 23) {
                        int hasWRITE_EXTERNAL_STORAGE = parentActivity
                                .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                            writeToStoragePermitted = false;
                            if (!parentActivity.shouldShowRequestPermissionRationale(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                        .setPositiveButton(context.getText(android.R.string.yes),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        if (android.os.Build.VERSION.SDK_INT >= 23)
                                                            parentActivity.requestPermissions(new String[] {
                                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                    MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                    }
                                                })
                                        .setNegativeButton(context.getText(android.R.string.no), null).show();
                            } else {
                                parentActivity.requestPermissions(
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                            }
                        }
                    }
                    if (writeToStoragePermitted) {
                        final Uri local = Uri.parse(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        new ImageDownloadTask(null, local.getPath()) {
                            @Override
                            protected void onPostExecute(Bitmap result) {
                                Uri myUri = Uri.fromFile(new File(local.getPath()));
                                Intent sharingIntent = new Intent();
                                sharingIntent.setAction(Intent.ACTION_SEND);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
                                sharingIntent.setType("image/png");
                                sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                context.startActivity(Intent.createChooser(sharingIntent,
                                        getResources().getString(R.string.action_share_dotdotdot)));
                            }
                        }.execute(url);
                    }
                } else {
                    Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
                }

                break;

            case ID_IMAGE_EXTERNAL_BROWSER:
                if (url != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                }
                break;

            //Copy url to clipboard
            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) context
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            //Try to share link to other apps
            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    context.startActivity(Intent.createChooser(sendIntent,
                            getResources().getText(R.string.context_menu_share_link)));
                }
                break;
            }
            return true;
        }
    };

    //Build context menu
    if (result.getType() == HitTestResult.IMAGE_TYPE
            || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        // Menu options for an image.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0,
                context.getString(R.string.context_menu_open_external_browser))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == HitTestResult.ANCHOR_TYPE
            || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
        // Menu options for a hyperlink.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link))
                .setOnMenuItemClickListener(handler);
    }
}