Example usage for android.text.util Linkify addLinks

List of usage examples for android.text.util Linkify addLinks

Introduction

In this page you can find the example usage for android.text.util Linkify addLinks.

Prototype

public static final boolean addLinks(@NonNull TextView text, @LinkifyMask int mask) 

Source Link

Document

Scans the text of the provided TextView and turns all occurrences of the link types indicated in the mask into clickable links.

Usage

From source file:com.acrylicgoat.devchat.MainActivity.java

private void getToday(String owner) {
    //Log.d("MainActivity", "getToday() called: " + owner);

    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery(getTodaySQL(), null);
    if (cursor.getCount() > 0) {
        cursor.moveToNext();//  w ww  . ja va  2s  .c  o m
        int notesColumn = cursor.getColumnIndex(Notes.NOTE);
        today.setText(cursor.getString(notesColumn));

    } else {
        if (devs.size() > 0) {
            today.setText("");
        } else {
            today.setText(getString(R.string.no_devs));

        }

    }
    Linkify.addLinks(today, Linkify.ALL);
    cursor.close();
    db.close();
}

From source file:com.facebook.android.GraphExplorer.java

public void setText(final String txt) {
    mHandler.post(new Runnable() {

        /*/*from   w  ww  .  jav  a 2 s. c o  m*/
         * A transform filter that simply returns just the text captured by
         * the first regular expression group.
         */
        TransformFilter idFilter = new TransformFilter() {
            @Override
            public final String transformUrl(final Matcher match, String url) {
                return match.group(1);
            }
        };

        @Override
        public void run() {
            mViewURLButton.setVisibility(TextUtils.isEmpty(txt) ? View.INVISIBLE : View.VISIBLE);
            mFieldsConnectionsButton.setVisibility(TextUtils.isEmpty(txt) ? View.INVISIBLE : View.VISIBLE);
            mOutput.setVisibility(TextUtils.isEmpty(txt) ? View.INVISIBLE : View.VISIBLE);
            mBackParentButton.setVisibility(TextUtils.isEmpty(mParentObjectId) ? View.INVISIBLE : View.VISIBLE);

            String convertedTxt = txt.replace("\\/", "/");
            mOutput.setText(convertedTxt);
            mScrollView.scrollTo(0, 0);

            Linkify.addLinks(mOutput, Linkify.WEB_URLS);
            /*
             * Linkify the object ids so they can be clicked. match pattern:
             * "id" : "objectid" (objectid can be int or int_int)
             */
            Pattern pattern = Pattern.compile("\"id\": \"(\\d*_?\\d*)\"");
            String scheme = "fbGraphEx://";
            Linkify.addLinks(mOutput, pattern, scheme, null, idFilter);
        }
    });
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Resources resources = getResources();

    TwoStatePreference runningPref = findPref("running_switch");
    updateRunningState();/*from   w  w  w.j a va 2 s .  c o m*/
    runningPref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((Boolean) newValue) {
            startServer();
        } else {
            stopServer();
        }
        return true;
    });

    PreferenceScreen prefScreen = findPref("preference_screen");
    Preference marketVersionPref = findPref("market_version");
    marketVersionPref.setOnPreferenceClickListener(preference -> {
        // start the market at our application
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=be.ppareit.swiftp"));
        try {
            // this can fail if there is no market installed
            startActivity(intent);
        } catch (Exception e) {
            Cat.e("Failed to launch the market.");
            e.printStackTrace();
        }
        return false;
    });
    if (!App.isFreeVersion()) {
        prefScreen.removePreference(marketVersionPref);
    }

    updateLoginInfo();

    EditTextPreference usernamePref = findPref("username");
    usernamePref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newUsername = (String) newValue;
        if (preference.getSummary().equals(newUsername))
            return false;
        if (!newUsername.matches("[a-zA-Z0-9]+")) {
            Toast.makeText(getActivity(), R.string.username_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        stopServer();
        return true;
    });

    mPassWordPref = findPref("password");
    mPassWordPref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });
    mAutoconnectListPref = findPref("autoconnect_preference");
    mAutoconnectListPref.setOnPopulateListener(pref -> {
        Cat.d("autoconnect populate listener");

        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs == null) {
            Cat.e("Unable to receive wifi configurations, bark at user and bail");
            Toast.makeText(getActivity(), R.string.autoconnect_error_enable_wifi_for_access_points,
                    Toast.LENGTH_LONG).show();
            return;
        }
        CharSequence[] ssids = new CharSequence[configs.size()];
        CharSequence[] niceSsids = new CharSequence[configs.size()];
        for (int i = 0; i < configs.size(); ++i) {
            ssids[i] = configs.get(i).SSID;
            String ssid = configs.get(i).SSID;
            if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            niceSsids[i] = ssid;
        }
        pref.setEntries(niceSsids);
        pref.setEntryValues(ssids);
    });
    mAutoconnectListPref.setOnPreferenceClickListener(preference -> {
        Cat.d("Clicked");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    new AlertDialog.Builder(getContext()).setTitle(R.string.request_coarse_location_dlg_title)
                            .setMessage(R.string.request_coarse_location_dlg_message)
                            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                                requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                                        ACCESS_COARSE_LOCATION_REQUEST_CODE);
                            }).setOnCancelListener(dialog -> {
                                mAutoconnectListPref.getDialog().cancel();
                            }).create().show();
                } else {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                            ACCESS_COARSE_LOCATION_REQUEST_CODE);
                }
            }
        }
        return false;
    });

    EditTextPreference portnum_pref = findPref("portNum");
    portnum_pref.setSummary(sp.getString("portNum", resources.getString(R.string.portnumber_default)));
    portnum_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newPortnumString = (String) newValue;
        if (preference.getSummary().equals(newPortnumString))
            return false;
        int portnum = 0;
        try {
            portnum = Integer.parseInt(newPortnumString);
        } catch (Exception e) {
            Cat.d("Error parsing port number! Moving on...");
        }
        if (portnum <= 0 || 65535 < portnum) {
            Toast.makeText(getActivity(), R.string.port_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        preference.setSummary(newPortnumString);
        stopServer();
        return true;
    });

    Preference chroot_pref = findPref("chrootDir");
    chroot_pref.setSummary(FsSettings.getChrootDirAsString());
    chroot_pref.setOnPreferenceClickListener(preference -> {
        AlertDialog folderPicker = new FolderPickerDialogBuilder(getActivity(), FsSettings.getChrootDir())
                .setSelectedButton(R.string.select, path -> {
                    if (preference.getSummary().equals(path))
                        return;
                    if (!FsSettings.setChrootDir(path))
                        return;
                    // TODO: this is a hotfix, create correct resources, improve UI/UX
                    final File root = new File(path);
                    if (!root.canRead()) {
                        Toast.makeText(getActivity(), "Notice that we can't read/write in this folder.",
                                Toast.LENGTH_LONG).show();
                    } else if (!root.canWrite()) {
                        Toast.makeText(getActivity(),
                                "Notice that we can't write in this folder, reading will work. Writing in sub folders might work.",
                                Toast.LENGTH_LONG).show();
                    }

                    preference.setSummary(path);
                    stopServer();
                }).setNegativeButton(R.string.cancel, null).create();
        folderPicker.show();
        return true;
    });

    final CheckBoxPreference wakelock_pref = findPref("stayAwake");
    wakelock_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });

    final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
    String externalStorageUri = FsSettings.getExternalStorageUri();
    if (externalStorageUri == null) {
        writeExternalStorage_pref.setChecked(false);
    }
    writeExternalStorage_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((boolean) newValue) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, ACTION_OPEN_DOCUMENT_TREE);
            return false;
        } else {
            FsSettings.setExternalStorageUri(null);
            return true;
        }
    });

    ListPreference theme = findPref("theme");
    theme.setSummary(theme.getEntry());
    theme.setOnPreferenceChangeListener((preference, newValue) -> {
        theme.setSummary(theme.getEntry());
        getActivity().recreate();
        return true;
    });

    Preference help = findPref("help");
    help.setOnPreferenceClickListener(preference -> {
        Cat.v("On preference help clicked");
        Context context = getActivity();
        AlertDialog ad = new AlertDialog.Builder(context).setTitle(R.string.help_dlg_title)
                .setMessage(R.string.help_dlg_message).setPositiveButton(android.R.string.ok, null).create();
        ad.show();
        Linkify.addLinks((TextView) ad.findViewById(android.R.id.message), Linkify.ALL);
        return true;
    });

    Preference about = findPref("about");
    about.setOnPreferenceClickListener(preference -> {
        startActivity(new Intent(getActivity(), AboutActivity.class));
        return true;
    });

}

From source file:com.quarterfull.newsAndroid.LoginDialogFragment.java

public static void ShowAlertDialog(String title, String text, Activity activity) {
    // Linkify the message
    final SpannableString s = new SpannableString(text);
    Linkify.addLinks(s, Linkify.ALL);

    AlertDialog aDialog = new AlertDialog.Builder(activity).setTitle(title).setMessage(s)
            .setPositiveButton(activity.getString(android.R.string.ok), null).create();
    aDialog.show();//from  w  w w  .ja v a2 s  .c o  m

    // Make the textview clickable. Must be called after show()
    ((TextView) aDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:de.baumann.thema.FragmentSound.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.help:
        SpannableString s;//from ww  w. j  a va2 s.c o  m

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            s = new SpannableString(Html.fromHtml(getString(R.string.help_sound), Html.FROM_HTML_MODE_LEGACY));
        } else {
            //noinspection deprecation
            s = new SpannableString(Html.fromHtml(getString(R.string.help_sound)));
        }
        Linkify.addLinks(s, Linkify.WEB_URLS);

        final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.sound)
                .setMessage(s).setPositiveButton(getString(R.string.yes), null);
        dialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:in.animeshpathak.nextbus.NextBusMain.java

/**
 * Creates the Application Info dialog with clickable links.
 * // w  w w. jav  a 2  s. c  o m
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private void showVersionInfoDialog() throws UnsupportedEncodingException, IOException {
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle(getString(R.string.app_name) + " " + getString(R.string.version_name));

    AssetManager assetManager = getResources().getAssets();
    String versionInfoFile = getString(R.string.versioninfo_asset);
    InputStreamReader reader = new InputStreamReader(assetManager.open(versionInfoFile), "UTF-8");
    BufferedReader br = new BufferedReader(reader);
    StringBuffer sbuf = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        sbuf.append(line);
        sbuf.append("\r\n");
    }

    final ScrollView scroll = new ScrollView(this);
    final TextView message = new TextView(this);
    final SpannableString sWlinks = new SpannableString(sbuf.toString());
    Linkify.addLinks(sWlinks, Linkify.WEB_URLS);
    message.setText(sWlinks);
    message.setMovementMethod(LinkMovementMethod.getInstance());
    message.setPadding(15, 15, 15, 15);
    scroll.addView(message);
    alertDialog.setView(scroll);
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // nothing to do, just dismiss dialog
        }
    });
    alertDialog.show();
}

From source file:com.keepassdroid.EntryActivity.java

private void showSamsungDialog() {
    String text = getString(R.string.clipboard_error).concat(System.getProperty("line.separator"))
            .concat(getString(R.string.clipboard_error_url));
    SpannableString s = new SpannableString(text);
    TextView tv = new TextView(this);
    tv.setText(s);//from   w w  w  . j ava  2s.  c om
    tv.setAutoLinkMask(RESULT_OK);
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    Linkify.addLinks(s, Linkify.WEB_URLS);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.clipboard_error_title)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setView(tv).show();

}

From source file:com.google.samples.apps.iosched.myschedule.MyScheduleActivity.java

private void showAnnouncementDialogIfNeeded(Intent intent) {
    final String title = intent.getStringExtra(EXTRA_DIALOG_TITLE);
    final String message = intent.getStringExtra(EXTRA_DIALOG_MESSAGE);

    if (!mShowedAnnouncementDialog && !TextUtils.isEmpty(title) && !TextUtils.isEmpty(message)) {
        LOGD(TAG, "showAnnouncementDialogIfNeeded, title: " + title);
        LOGD(TAG, "showAnnouncementDialogIfNeeded, message: " + message);
        final String yes = intent.getStringExtra(EXTRA_DIALOG_YES);
        LOGD(TAG, "showAnnouncementDialogIfNeeded, yes: " + yes);
        final String no = intent.getStringExtra(EXTRA_DIALOG_NO);
        LOGD(TAG, "showAnnouncementDialogIfNeeded, no: " + no);
        final String url = intent.getStringExtra(EXTRA_DIALOG_URL);
        LOGD(TAG, "showAnnouncementDialogIfNeeded, url: " + url);
        final SpannableString spannable = new SpannableString(message == null ? "" : message);
        Linkify.addLinks(spannable, Linkify.WEB_URLS);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (!TextUtils.isEmpty(title)) {
            builder.setTitle(title);/*ww w. ja  v a2 s.c o  m*/
        }
        builder.setMessage(spannable);
        if (!TextUtils.isEmpty(no)) {
            builder.setNegativeButton(no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
        }
        if (!TextUtils.isEmpty(yes)) {
            builder.setPositiveButton(yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
            });
        }
        final AlertDialog dialog = builder.create();
        dialog.show();
        final TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
        if (messageView != null) {
            // makes the embedded links in the text clickable, if there are any
            messageView.setMovementMethod(LinkMovementMethod.getInstance());
        }
        mShowedAnnouncementDialog = true;
    }
}

From source file:com.todoroo.astrid.adapter.TaskAdapter.java

private void showEditNotesDialog(final Task task) {
    Task t = taskDao.fetch(task.getId(), Task.NOTES);
    if (t == null || !t.hasNotes()) {
        return;//from  w  w w  .jav  a2  s .  c om
    }
    SpannableString description = new SpannableString(t.getNotes());
    Linkify.addLinks(description, Linkify.ALL);
    AlertDialog dialog = dialogBuilder.newDialog().setMessage(description)
            .setPositiveButton(android.R.string.ok, null).show();
    View message = dialog.findViewById(android.R.id.message);
    if (message != null && message instanceof TextView) {
        ((TextView) message).setMovementMethod(LinkMovementMethod.getInstance());
    }
}

From source file:com.musiqueplayer.playlistequalizerandroidwear.activities.MainActivity.java

private void updatePosition(final MenuItem menuItem) {
    runnable = null;//from  ww  w.j  a v  a  2  s.  c o  m

    switch (menuItem.getItemId()) {
    case R.id.nav_library:
        runnable = navigateLibrary;

        break;
    case R.id.nav_playlists:
        runnable = navigatePlaylist;

        break;
    case R.id.nav_folders:
        runnable = navigateFolder;

        break;
    case R.id.nav_nowplaying:
        NavigationUtils.navigateToNowplaying(MainActivity.this, false);
        break;
    case R.id.nav_queue:
        runnable = navigateQueue;

        break;
    case R.id.nav_timer:
        runnable = navigateTimer;

        break;
    case R.id.nav_settings:
        NavigationUtils.navigateToSettings(MainActivity.this);
        break;
    case R.id.nav_about:
        mDrawerLayout.closeDrawers();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                final String APP_PNAME = "com.musiqueplayer.playlistequalizerandroidwear";
                final Context mContext = getApplicationContext();
                final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        new ContextThemeWrapper(MainActivity.this, R.style.myDialog));

                final SpannableString s = new SpannableString(
                        Html.fromHtml("Thanks for downloading Music Player.<br>"
                                + "Thanks for being an awesome user! If you enjoy using <b>Music Player</b> app, please take a moment to rate it with <b>5 stars</b>. "
                                + ""));
                Linkify.addLinks(s, Linkify.ALL);

                alertDialogBuilder.setTitle("About");
                alertDialogBuilder.setMessage(s);

                alertDialogBuilder.setPositiveButton("Rate Now", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        mContext.startActivity(
                                new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));

                    }
                });

                alertDialogBuilder.setNegativeButton("Remind Later", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putLong("launch_count", 0);
                        editor.commit();
                    }
                });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();

            }
        }, 350);

        break;
    }

    if (runnable != null) {
        menuItem.setChecked(true);
        mDrawerLayout.closeDrawers();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                runnable.run();
            }
        }, 350);
    }
}