Example usage for android.content ClipData newPlainText

List of usage examples for android.content ClipData newPlainText

Introduction

In this page you can find the example usage for android.content ClipData newPlainText.

Prototype

static public ClipData newPlainText(CharSequence label, CharSequence text) 

Source Link

Document

Create a new ClipData holding data of the type ClipDescription#MIMETYPE_TEXT_PLAIN .

Usage

From source file:com.ruesga.rview.fragments.DownloadDialogFragment.java

private void performCopyCommand(String label, String command) {
    // Check we still in a valid context
    if (getActivity() == null) {
        return;//  w  ww .  jav a 2s  . c  o  m
    }

    // Copy to clipboard
    ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText(label, command);
    clipboard.setPrimaryClip(clip);

    // Show a confirmation message
    final String msg = getString(R.string.download_commands_dialog_copy_message, label);
    Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}

From source file:com.klinker.android.twitter.activities.tweet_viewer.TweetPager.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();//from   w w  w. ja  v a 2 s  .  c  o m
        return true;

    case R.id.menu_delete_tweet:
        new DeleteTweet().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences", 0).edit()
                .putBoolean("just_muted", true).commit();
        return true;

    case R.id.menu_share:
        String text1 = tweet;
        text1 = "@" + screenName + ": " + text1 + "\n\n" + "https://twitter.com/" + screenName + "/status/"
                + tweetId;
        Log.v("my_text_on_share", text1);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(Intent.EXTRA_TEXT, text1);

        startActivity(share);
        return true;

    case R.id.menu_copy_text:
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("tweet_text", tweet);
        clipboard.setPrimaryClip(clip);
        return true;

    /*case R.id.menu_open_web:
        Uri weburi;
        try {
            weburi = Uri.parse(otherLinks[0]);
        } catch (Exception e) {
            weburi = Uri.parse(webpage);
        }
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, weburi);
        startActivity(launchBrowser);
            
        return true;*/

    case R.id.menu_save_image:

        new Thread(new Runnable() {
            @Override
            public void run() {

                Looper.prepare();

                try {
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.downloading) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saving_picture) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());

                    String url = webpage;
                    if (webpage.contains("insta")) {
                        url = url.substring(0, url.length() - 1) + "l";
                    }
                    URL mUrl = new URL(url);

                    Bitmap bitmap = BitmapFactory.decodeStream(mUrl.openConnection().getInputStream());

                    Random generator = new Random();
                    int n = 1000000;
                    n = generator.nextInt(n);
                    String fname = "Image-" + n;

                    Uri uri = IOUtils.saveImage(bitmap, fname, context);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "image/*");

                    PendingIntent pending = PendingIntent.getActivity(context, 91, intent, 0);

                    mBuilder = new NotificationCompat.Builder(context).setContentIntent(pending)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.saved_picture) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saved_picture) + "!")
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                                    R.drawable.ic_action_save));

                    mNotificationManager.notify(6, mBuilder.build());
                } catch (Exception e) {
                    e.printStackTrace();
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.error) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.error) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());
                }
            }
        }).start();

        return true;

    case R.id.menu_quote:
        String text = tweet;

        switch (settings.quoteStyle) {
        case AppSettings.QUOTE_STYLE_TWITTER:
            text = " " + "https://twitter.com/" + screenName + "/status/" + tweetId;
            break;
        case AppSettings.QUOTE_STYLE_TALON:
            text = "\"@" + screenName + ": " + text + "\" ";
            break;
        case AppSettings.QUOTE_STYLE_RT:
            text = " RT @" + screenName + ": " + text;
            break;
        }

        Intent quote = new Intent(context, ComposeActivity.class);
        quote.putExtra("user", text);
        quote.putExtra("id", tweetId);

        startActivity(quote);

        return true;

    case R.id.menu_spam:
        new MarkSpam().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences", 0).edit()
                .putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);

    /*case R.id.menu_mute_hashtags:
        if (!hashtags[0].equals("")) {
            ArrayList<String> tags = new ArrayList<String>();
            if (hashtags != null) {
                for (String s : hashtags) {
                    if (!s.equals("")) {
                        tags.add("#" + s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[tags.size()];
            
            for (int i = 0; i < tags.size(); i++) {
                fItems[i] = tags.get(i);
            }
            
            final SharedPreferences sharedPreferences = context.getSharedPreferences("com.klinker.android.twitter_world_preferences",
                    0);
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
                        Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                        touched = touched.replace("#", "") + " ";
            
                        String current = sharedPreferences.getString("muted_hashtags", "");
                        sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                        sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
                Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                touched = touched.replace("#", "") + " ";
            
                String current = sharedPreferences.getString("muted_hashtags", "");
                sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_hashtags), Toast.LENGTH_SHORT).show();
        }
            
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);
            
    case R.id.menu_share_links:
        if (!otherLinks[0].equals("")) {
            ArrayList<String> urls = new ArrayList<String>();
            if (otherLinks != null) {
                for (String s : otherLinks) {
                    if (!s.equals("")) {
                        urls.add(s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[urls.size()];
            
            for (int i = 0; i < urls.size(); i++) {
                fItems[i] = urls.get(i);
            }
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
            
                        Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                        intent.setType("text/plain");
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        intent.putExtra(Intent.EXTRA_TEXT, touched);
                        context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
            
                Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.putExtra(Intent.EXTRA_TEXT, touched);
                context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_links), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);*/
    case R.id.menu_translate:
        try {
            String url = settings.translateURL + tweet;

            Uri uri = Uri.parse(url);

            Intent browser = new Intent(Intent.ACTION_VIEW, uri);
            browser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(browser);
        } catch (Exception e) {

        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:de.grobox.liberario.utils.TransportrUtils.java

static public void copyToClipboard(Context context, String text) {
    ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("label", text);
    clipboard.setPrimaryClip(clip);//  ww w. j  ava  2 s. c o m
}

From source file:com.klinker.android.twitter.ui.tweet_viewer.TweetPager.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();//from  w  ww. ja va  2  s. c  o m
        return true;

    case R.id.menu_delete_tweet:
        new DeleteTweet().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE).edit()
                        .putBoolean("just_muted", true).commit();
        return true;

    case R.id.menu_share:
        String text1 = tweet;
        text1 = "@" + screenName + ": " + text1 + "\n\n" + "https://twitter.com/" + screenName + "/status/"
                + tweetId;
        Log.v("my_text_on_share", text1);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(Intent.EXTRA_TEXT, text1);

        startActivity(share);
        return true;

    case R.id.menu_copy_text:
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("tweet_text", tweet);
        clipboard.setPrimaryClip(clip);
        return true;

    /*case R.id.menu_open_web:
        Uri weburi;
        try {
            weburi = Uri.parse(otherLinks[0]);
        } catch (Exception e) {
            weburi = Uri.parse(webpage);
        }
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, weburi);
        startActivity(launchBrowser);
            
        return true;*/

    case R.id.menu_save_image:

        new Thread(new Runnable() {
            @Override
            public void run() {

                Looper.prepare();

                try {
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.downloading) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saving_picture) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());

                    String url = webpage;
                    if (webpage.contains("insta")) {
                        url = url.substring(0, url.length() - 1) + "l";
                    }
                    URL mUrl = new URL(url);

                    Bitmap bitmap = BitmapFactory.decodeStream(mUrl.openConnection().getInputStream());

                    Random generator = new Random();
                    int n = 1000000;
                    n = generator.nextInt(n);
                    String fname = "Image-" + n;

                    Uri uri = IOUtils.saveImage(bitmap, fname, context);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "image/*");

                    PendingIntent pending = PendingIntent.getActivity(context, 91, intent, 0);

                    mBuilder = new NotificationCompat.Builder(context).setContentIntent(pending)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.saved_picture) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saved_picture) + "!")
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                                    R.drawable.ic_action_save));

                    mNotificationManager.notify(6, mBuilder.build());
                } catch (Exception e) {
                    e.printStackTrace();
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.error) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.error) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());
                }
            }
        }).start();

        return true;

    case R.id.menu_quote:
        String text = tweet;

        if (!settings.preferRT) {
            text = "\"@" + screenName + ": " + text + "\" ";
        } else {
            text = " RT @" + screenName + ": " + text;
        }

        Intent quote = new Intent(context, ComposeActivity.class);
        quote.putExtra("user", text);
        quote.putExtra("id", tweetId);

        startActivity(quote);

        return true;

    case R.id.menu_spam:
        new MarkSpam().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE).edit()
                        .putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);

    /*case R.id.menu_mute_hashtags:
        if (!hashtags[0].equals("")) {
            ArrayList<String> tags = new ArrayList<String>();
            if (hashtags != null) {
                for (String s : hashtags) {
                    if (!s.equals("")) {
                        tags.add("#" + s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[tags.size()];
            
            for (int i = 0; i < tags.size(); i++) {
                fItems[i] = tags.get(i);
            }
            
            final SharedPreferences sharedPreferences = context.getSharedPreferences("com.klinker.android.twitter_world_preferences",
                    Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
                        Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                        touched = touched.replace("#", "") + " ";
            
                        String current = sharedPreferences.getString("muted_hashtags", "");
                        sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                        sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
                Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                touched = touched.replace("#", "") + " ";
            
                String current = sharedPreferences.getString("muted_hashtags", "");
                sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_hashtags), Toast.LENGTH_SHORT).show();
        }
            
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);
            
    case R.id.menu_share_links:
        if (!otherLinks[0].equals("")) {
            ArrayList<String> urls = new ArrayList<String>();
            if (otherLinks != null) {
                for (String s : otherLinks) {
                    if (!s.equals("")) {
                        urls.add(s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[urls.size()];
            
            for (int i = 0; i < urls.size(); i++) {
                fItems[i] = urls.get(i);
            }
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
            
                        Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                        intent.setType("text/plain");
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        intent.putExtra(Intent.EXTRA_TEXT, touched);
                        context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
            
                Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.putExtra(Intent.EXTRA_TEXT, touched);
                context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_links), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);*/
    case R.id.menu_translate:
        try {
            String query = tweet.replaceAll(" ", "+");
            String url = "http://translate.google.com/#auto|en|" + tweet;
            Uri uri = Uri.parse(url);

            Intent browser = new Intent(Intent.ACTION_VIEW, uri);
            browser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(browser);
        } catch (Exception e) {

        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:de.blinkt.openvpn.fragments.LogFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ListView lv = getListView();//from  w w w  .j  a  v  a 2  s . c  o m

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            ClipboardManager clipboard = (ClipboardManager) getActivity()
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Log Entry", ((TextView) view).getText());
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getActivity(), R.string.copied_entry, Toast.LENGTH_SHORT).show();
            return true;
        }
    });
}

From source file:com.projects.nosleepreader.MainActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (mFrag.scrollLoading) {
        Toast.makeText(this, LOADING_TOAST_TEXT, Toast.LENGTH_SHORT);
        return true;
    }/*from   www  .  j  a  v a  2  s.c o  m*/
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int id = item.getItemId();
    switch (id) {
    case R.id.copy_url:
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label",
                mValuesArray.get(info.position).getAsString(ListingDbHelper.COLUMN_URL));
        clipboard.setPrimaryClip(clip);
        break;
    case R.id.context_menu_favorite:
        if (mCurrentTable.equals(ListingDbHelper.TABLE_NAME_FAVORITES)) {
            mPosition = (info.position - 1 >= 0) ? info.position - 1 : 0;
            mDbHelper.deleteFavoites(mValuesArray.get(info.position).getAsString(ListingDbHelper.COLUMN_ID));
            mFrag.getFavorites(mValuesArray);
        } else
            mDbHelper.insertFavorites(mValuesArray.get(info.position));
        break;
    case R.id.context_menu_author:
        String author = mValuesArray.get(info.position).getAsString(ListingDbHelper.COLUMN_AUTHOR);
        getSupportActionBar().setTitle("Submissions By " + author);
        firstRun = true;
        mCurrentTable = CURRENT_AUTHOR_TAG;
        mAuthor = "author:" + author;
        resetList();
        mFrag.getAuthor(mAfter, mValuesArray, count, mAuthor);
    }
    return super.onContextItemSelected(item);
}

From source file:com.fa.imaged.activity.DetailActivityV2.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    int id = item.getItemId();
    switch (id) {

    case android.R.id.home:
        ActivityCompat.finishAfterTransition(this);
        return true;

    case R.id.save_photo:

        try {//from  w ww  .ja v a2s.c o m
            new ImageDownloader().execute(detailImageLoaderv2.standard_resolution);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, "Error saving image", Toast.LENGTH_SHORT);
        }
        return true;

    case R.id.copy_link:
        if (detailImageLoaderv2.permalink != null) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Post Link", detailImageLoaderv2.permalink);
            clipboard.setPrimaryClip(clip);
            Toast.makeText(this, "Link Copied", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Cannot copy link", Toast.LENGTH_SHORT);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:de.baumann.browser.Browser.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    final WebView.HitTestResult result = mWebView.getHitTestResult();

    final MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            final String url = result.getExtra();

            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                try {
                    if (url != null) {

                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(
                                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                helper_main.newFileName());
                        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                        dm.enqueue(request);

                        Snackbar.make(mWebView,
                                getString(R.string.context_saveImage_toast) + " " + helper_main.newFileName(),
                                Snackbar.LENGTH_SHORT).show();
                    }/*from ww  w.  ja  v a2 s.c  om*/
                } catch (Exception e) {
                    e.printStackTrace();
                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {

                    shareString = helper_main.newFileName();
                    shareFile = helper_main.newFile();

                    try {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(
                                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, shareString);
                        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                        dm.enqueue(request);

                        Snackbar.make(mWebView,
                                getString(R.string.context_saveImage_toast) + " " + helper_main.newFileName(),
                                Snackbar.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                    }
                    registerReceiver(onComplete2, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                }
                break;

            case ID_READ_LATER:
                if (url != null) {
                    int domainInt = url.indexOf("//") + 2;
                    final String domain = url.substring(domainInt, url.indexOf('/', domainInt));

                    try {
                        final Database_ReadLater db = new Database_ReadLater(Browser.this);
                        db.addBookmark(domain, url);
                        db.close();
                        Snackbar.make(mWebView, R.string.readLater_added, Snackbar.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;

            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) Browser.this
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT).show();
                }
                break;

            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");
                    Browser.this.startActivity(Intent.createChooser(sendIntent,
                            getResources().getString(R.string.app_share_link)));
                }
                break;
            }
            return true;
        }
    };

    if (result.getType() == WebView.HitTestResult.IMAGE_TYPE) {
        menu.add(0, ID_SAVE_IMAGE, 0, getString(R.string.context_saveImage))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, getString(R.string.context_shareImage))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_READ_LATER, 0, getString(R.string.context_readLater))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
        menu.add(0, ID_COPY_LINK, 0, getString(R.string.menu_share_link_copy))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, getString(R.string.menu_share_link)).setOnMenuItemClickListener(handler);
        menu.add(0, ID_READ_LATER, 0, getString(R.string.context_readLater))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:de.gebatzens.sia.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(SIAApp.SIA_APP.school.getTheme());
    super.onCreate(savedInstanceState);
    Log.w("ggvp", "CREATE NEW MAINACTIVITY");
    //Debug.startMethodTracing("sia3");
    SIAApp.SIA_APP.activity = this;
    savedState = savedInstanceState;/* w  w  w. j a  v  a  2s.  c  o m*/

    final FragmentData.FragmentList fragments = SIAApp.SIA_APP.school.fragments;

    Intent intent = getIntent();
    if (intent != null && intent.getStringExtra("fragment") != null) {
        FragmentData frag = fragments
                .getByType(FragmentData.FragmentType.valueOf(intent.getStringExtra("fragment"))).get(0);
        SIAApp.SIA_APP.setFragmentIndex(fragments.indexOf(frag));
    }

    if (intent != null && intent.getBooleanExtra("reload", false)) {
        SIAApp.SIA_APP.refreshAsync(null, true, fragments.get(SIAApp.SIA_APP.getFragmentIndex()));
        intent.removeExtra("reload");
    }

    setContentView(R.layout.activity_main);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    mContent = getFragment();
    transaction.replace(R.id.content_fragment, mContent, "gg_content_fragment");
    transaction.commit();

    Log.d("ggvp", "DATA: " + fragments.get(SIAApp.SIA_APP.getFragmentIndex()).getData());
    if (fragments.get(SIAApp.SIA_APP.getFragmentIndex()).getData() == null)
        SIAApp.SIA_APP.refreshAsync(null, true, fragments.get(SIAApp.SIA_APP.getFragmentIndex()));

    if ("Summer".equals(SIAApp.SIA_APP.getCurrentThemeName())) {
        ImageView summerNavigationPalm = (ImageView) findViewById(R.id.summer_navigation_palm);
        summerNavigationPalm.setImageResource(R.drawable.summer_palm);
        ImageView summerBackgroundImage = (ImageView) findViewById(R.id.summer_background_image);
        summerBackgroundImage.setImageResource(R.drawable.summer_background);
    }

    mToolBar = (Toolbar) findViewById(R.id.toolbar);
    mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {

            switch (menuItem.getItemId()) {
            case R.id.action_refresh:
                ((SwipeRefreshLayout) mContent.getView().findViewById(R.id.refresh)).setRefreshing(true);
                SIAApp.SIA_APP.refreshAsync(new Runnable() {
                    @Override
                    public void run() {
                        ((SwipeRefreshLayout) mContent.getView().findViewById(R.id.refresh))
                                .setRefreshing(false);
                    }
                }, true, fragments.get(SIAApp.SIA_APP.getFragmentIndex()));
                return true;
            case R.id.action_settings:
                Intent i = new Intent(MainActivity.this, SettingsActivity.class);
                startActivityForResult(i, 1);
                return true;
            case R.id.action_addToCalendar:
                showExamDialog();
                return true;
            case R.id.action_help:
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getApplication().getString(R.string.help));
                builder.setMessage(getApplication().getString(R.string.exam_explain));
                builder.setPositiveButton(getApplication().getString(R.string.close),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                return true;
            }

            return false;
        }
    });

    updateToolbar(SIAApp.SIA_APP.school.name, fragments.get(SIAApp.SIA_APP.getFragmentIndex()).name);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        SIAApp.SIA_APP.setStatusBarColorTransparent(getWindow()); // because of the navigation drawer
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.addDrawerListener(mDrawerToggle);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    mNavigationHeader = navigationView.getHeaderView(0);
    mNavigationSchoolpictureText = (TextView) mNavigationHeader.findViewById(R.id.drawer_image_text);
    mNavigationSchoolpictureText.setText(SIAApp.SIA_APP.school.name);
    mNavigationSchoolpicture = (ImageView) mNavigationHeader.findViewById(R.id.navigation_schoolpicture);
    mNavigationSchoolpicture.setImageBitmap(SIAApp.SIA_APP.school.loadImage());
    mNavigationSchoolpictureLink = mNavigationHeader.findViewById(R.id.navigation_schoolpicture_link);
    mNavigationSchoolpictureLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View viewIn) {
            mDrawerLayout.closeDrawers();
            Intent linkIntent = new Intent(Intent.ACTION_VIEW);
            linkIntent.setData(Uri.parse(SIAApp.SIA_APP.school.website));
            startActivity(linkIntent);
        }
    });

    final Menu menu = navigationView.getMenu();
    menu.clear();
    for (int i = 0; i < fragments.size(); i++) {
        MenuItem item = menu.add(R.id.fragments, Menu.NONE, i, fragments.get(i).name);
        item.setIcon(fragments.get(i).getIconRes());
    }

    menu.add(R.id.settings, R.id.settings_item, fragments.size(), R.string.settings);
    menu.setGroupCheckable(R.id.fragments, true, true);
    menu.setGroupCheckable(R.id.settings, false, false);

    final Menu navMenu = navigationView.getMenu();
    selectedItem = SIAApp.SIA_APP.getFragmentIndex();
    if (selectedItem != -1)
        navMenu.getItem(selectedItem).setChecked(true);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            if (menuItem.getItemId() == R.id.settings_item) {
                mDrawerLayout.closeDrawers();
                Intent i = new Intent(MainActivity.this, SettingsActivity.class);
                startActivityForResult(i, 1);
            } else {
                final int index = menuItem.getOrder();
                if (SIAApp.SIA_APP.getFragmentIndex() != index) {
                    SIAApp.SIA_APP.setFragmentIndex(index);
                    menuItem.setChecked(true);
                    updateToolbar(SIAApp.SIA_APP.school.name, menuItem.getTitle().toString());
                    mContent = getFragment();
                    Animation fadeOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);
                    fadeOut.setAnimationListener(new Animation.AnimationListener() {

                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            FrameLayout contentFrame = (FrameLayout) findViewById(R.id.content_fragment);
                            contentFrame.setVisibility(View.INVISIBLE);
                            if (fragments.get(index).getData() == null)
                                SIAApp.SIA_APP.refreshAsync(null, true, fragments.get(index));

                            //removeAllFragments();

                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                            transaction.replace(R.id.content_fragment, mContent, "gg_content_fragment");
                            transaction.commit();

                            snowView.updateSnow();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    FrameLayout contentFrame = (FrameLayout) findViewById(R.id.content_fragment);
                    contentFrame.startAnimation(fadeOut);
                    mDrawerLayout.closeDrawers();
                } else {
                    mDrawerLayout.closeDrawers();
                }
            }
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= 25) {
        ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
        shortcutManager.removeAllDynamicShortcuts();

        for (int i = 0; i < fragments.size(); i++) {
            Drawable drawable = getDrawable(fragments.get(i).getIconRes());
            Bitmap icon;
            if (drawable instanceof VectorDrawable) {
                icon = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                        Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(icon);
                drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                drawable.draw(canvas);
            } else {
                icon = BitmapFactory.decodeResource(getResources(), fragments.get(i).getIconRes());
            }

            Bitmap connectedIcon = Bitmap.createBitmap(icon.getWidth(), icon.getHeight(),
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(connectedIcon);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(Color.parseColor("#f5f5f5"));
            canvas.drawCircle(icon.getWidth() / 2, icon.getHeight() / 2, icon.getWidth() / 2, paint);
            paint.setColorFilter(
                    new PorterDuffColorFilter(SIAApp.SIA_APP.school.getColor(), PorterDuff.Mode.SRC_ATOP));
            canvas.drawBitmap(icon, null, new RectF(icon.getHeight() / 4.0f, icon.getHeight() / 4.0f,
                    icon.getHeight() - icon.getHeight() / 4.0f, icon.getHeight() - icon.getHeight() / 4.0f),
                    paint);

            Intent newTaskIntent = new Intent(this, MainActivity.class);
            newTaskIntent.setAction(Intent.ACTION_MAIN);
            newTaskIntent.putExtra("fragment", fragments.get(i).type.toString());

            ShortcutInfo shortcut = new ShortcutInfo.Builder(this, fragments.get(i).name)
                    .setShortLabel(fragments.get(i).name).setLongLabel(fragments.get(i).name)
                    .setIcon(Icon.createWithBitmap(connectedIcon)).setIntent(newTaskIntent).build();

            shortcutManager.addDynamicShortcuts(Arrays.asList(shortcut));
        }
    }

    if (SIAApp.SIA_APP.preferences.getBoolean("app_130_upgrade", true)) {
        if (!SIAApp.SIA_APP.preferences.getBoolean("first_use_filter", true)) {
            TextDialog.newInstance(R.string.upgrade1_3title, R.string.upgrade1_3)
                    .show(getSupportFragmentManager(), "upgrade_dialog");
        }

        SIAApp.SIA_APP.preferences.edit().putBoolean("app_130_upgrade", false).apply();
    }

    snowView = (SnowView) findViewById(R.id.snow_view);

    shareToolbar = (Toolbar) findViewById(R.id.share_toolbar);
    shareToolbar.getMenu().clear();
    shareToolbar.inflateMenu(R.menu.share_toolbar_menu);
    shareToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggleShareToolbar(false);
            for (Shareable s : MainActivity.this.shared) {
                s.setMarked(false);
            }
            MainActivity.this.shared.clear();

            mContent.updateFragment();
        }
    });

    shareToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            toggleShareToolbar(false);

            HashMap<Date, ArrayList<Shareable>> dates = new HashMap<Date, ArrayList<Shareable>>();

            for (Shareable s : MainActivity.this.shared) {
                ArrayList<Shareable> list = dates.get(s.getDate());
                if (list == null) {
                    list = new ArrayList<Shareable>();
                    dates.put(s.getDate(), list);
                }

                list.add(s);

                s.setMarked(false);
            }
            MainActivity.this.shared.clear();

            List<Date> dateList = new ArrayList<Date>(dates.keySet());
            Collections.sort(dateList);
            String content = "";

            for (Date key : dateList) {
                content += SubstListAdapter.translateDay(key) + "\n\n";

                Collections.sort(dates.get(key));
                for (Shareable s : dates.get(key)) {
                    content += s.getShareContent() + "\n";
                }

                content += "\n";
            }

            content = content.substring(0, content.length() - 1);

            mContent.updateFragment();

            if (item.getItemId() == R.id.action_copy) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

                ClipData clip = ClipData.newPlainText(getString(R.string.entries), content);
                clipboard.setPrimaryClip(clip);
            } else if (item.getItemId() == R.id.action_share) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, content);
                sendIntent.setType("text/plain");
                startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
            }

            return true;
        }
    });

    if (shared.size() > 0) {
        shareToolbar.setVisibility(View.VISIBLE);
        updateShareToolbarText();
    }

    // if a fragment is opened via a notification or a shortcut reset the shared entries
    // delete extra fragment because the same intent is used when the device gets rotated and the user could have opened a new fragment
    if (intent != null && intent.hasExtra("fragment")) {
        resetShareToolbar();
        intent.removeExtra("fragment");
    }

}

From source file:com.microsoft.onedrive.apiexplorer.ItemFragment.java

/**
 * Creates a link on this item/*from  w w w  . j  a  v  a  2  s.c o m*/
 * @param item The item to delete
 */
private void createLink(final Item item) {
    final CharSequence[] items = { "view", "edit" };
    final int nothingSelected = -1;
    final AtomicInteger selection = new AtomicInteger(nothingSelected);
    final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.create_link)
            .setIcon(android.R.drawable.ic_menu_share)
            .setPositiveButton(R.string.create_link, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    if (selection.get() == nothingSelected) {
                        return;
                    }

                    final BaseApplication application = (BaseApplication) getActivity().getApplication();
                    application.getOneDriveClient().getDrive().getItems(item.id)
                            .getCreateLink(items[selection.get()].toString()).buildRequest()
                            .create(new DefaultCallback<Permission>(getActivity()) {
                                @Override
                                public void success(final Permission permission) {
                                    final ClipboardManager cm = (ClipboardManager) getActivity()
                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                    final ClipData data = ClipData.newPlainText("Link Url",
                                            permission.link.webUrl);
                                    cm.setPrimaryClip(data);
                                    Toast.makeText(getActivity(), application.getString(R.string.created_link),
                                            Toast.LENGTH_LONG).show();
                                    getActivity().onBackPressed();
                                }
                            });
                }
            }).setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    selection.set(which);
                }
            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    dialog.cancel();
                }
            }).create();
    alertDialog.show();
}