Example usage for android.text.style ClickableSpan ClickableSpan

List of usage examples for android.text.style ClickableSpan ClickableSpan

Introduction

In this page you can find the example usage for android.text.style ClickableSpan ClickableSpan.

Prototype

ClickableSpan

Source Link

Usage

From source file:org.onebusaway.android.ui.ArrivalsListHeader.java

void initView(View view) {
    // Clear any existing arrival info
    mArrivalInfo = null;/*from  ww w.  ja  v a 2s  . c o m*/
    mHeaderArrivalInfo.clear();
    mNumHeaderArrivals = -1;

    // Cache the ArrivalsListHeader height values
    HEADER_HEIGHT_ONE_ARRIVAL_DP = view.getResources().getDimension(R.dimen.arrival_header_height_one_arrival)
            / view.getResources().getDisplayMetrics().density;
    HEADER_HEIGHT_TWO_ARRIVALS_DP = view.getResources().getDimension(R.dimen.arrival_header_height_two_arrivals)
            / view.getResources().getDisplayMetrics().density;
    HEADER_OFFSET_FILTER_ROUTES_DP = view.getResources()
            .getDimension(R.dimen.arrival_header_height_offset_filter_routes)
            / view.getResources().getDisplayMetrics().density;
    HEADER_HEIGHT_EDIT_NAME_DP = view.getResources().getDimension(R.dimen.arrival_header_height_edit_name)
            / view.getResources().getDisplayMetrics().density;

    // Init views
    mView = view;
    mMainContainerView = mView.findViewById(R.id.main_header_content);
    mNameContainerView = mView.findViewById(R.id.stop_name_and_info_container);
    mEditNameContainerView = mView.findViewById(R.id.edit_name_container);
    mNameView = (TextView) mView.findViewById(R.id.stop_name);
    mEditNameView = (EditText) mView.findViewById(R.id.edit_name);
    mStopFavorite = (ImageButton) mView.findViewById(R.id.stop_favorite);
    mStopFavorite.setColorFilter(mView.getResources().getColor(R.color.header_text_color));
    mFilterGroup = mView.findViewById(R.id.filter_group);

    mShowAllView = (TextView) mView.findViewById(R.id.show_all);
    // Remove any previous clickable spans - we're recycling views between fragments for efficiency
    UIUtils.removeAllClickableSpans(mShowAllView);
    mShowAllClick = new ClickableSpan() {
        public void onClick(View v) {
            mController.setRoutesFilter(new ArrayList<String>());
        }
    };
    UIUtils.setClickableSpan(mShowAllView, mShowAllClick);

    mNoArrivals = (TextView) mView.findViewById(R.id.no_arrivals);

    // First ETA row
    mEtaContainer1 = mView.findViewById(R.id.eta_container1);
    mEtaRouteFavorite1 = (ImageButton) mEtaContainer1.findViewById(R.id.eta_route_favorite);
    mEtaRouteFavorite1.setColorFilter(mView.getResources().getColor(R.color.header_text_color));
    mEtaReminder1 = (ImageButton) mEtaContainer1.findViewById(R.id.reminder);
    mEtaReminder1.setColorFilter(mView.getResources().getColor(R.color.header_text_color));
    mEtaRouteName1 = (TextView) mEtaContainer1.findViewById(R.id.eta_route_name);
    mEtaRouteDirection1 = (TextView) mEtaContainer1.findViewById(R.id.eta_route_direction);
    mEtaAndMin1 = (RelativeLayout) mEtaContainer1.findViewById(R.id.eta_and_min);
    mEtaArrivalInfo1 = (TextView) mEtaContainer1.findViewById(R.id.eta);
    mEtaMin1 = (TextView) mEtaContainer1.findViewById(R.id.eta_min);
    mEtaRealtime1 = (ViewGroup) mEtaContainer1.findViewById(R.id.eta_realtime_indicator);
    mEtaMoreVert1 = (ImageButton) mEtaContainer1.findViewById(R.id.eta_more_vert);
    mEtaMoreVert1.setColorFilter(mView.getResources().getColor(R.color.header_text_color));

    mEtaSeparator = mView.findViewById(R.id.eta_separator);

    // Second ETA row
    mEtaContainer2 = mView.findViewById(R.id.eta_container2);
    mEtaRouteFavorite2 = (ImageButton) mEtaContainer2.findViewById(R.id.eta_route_favorite);
    mEtaRouteFavorite2.setColorFilter(mView.getResources().getColor(R.color.header_text_color));
    mEtaReminder2 = (ImageButton) mEtaContainer2.findViewById(R.id.reminder);
    mEtaReminder2.setColorFilter(mView.getResources().getColor(R.color.header_text_color));
    mEtaRouteName2 = (TextView) mEtaContainer2.findViewById(R.id.eta_route_name);
    mEtaAndMin2 = (RelativeLayout) mEtaContainer2.findViewById(R.id.eta_and_min);
    mEtaRouteDirection2 = (TextView) mEtaContainer2.findViewById(R.id.eta_route_direction);
    mEtaArrivalInfo2 = (TextView) mEtaContainer2.findViewById(R.id.eta);
    mEtaMin2 = (TextView) mEtaContainer2.findViewById(R.id.eta_min);
    mEtaRealtime2 = (ViewGroup) mEtaContainer2.findViewById(R.id.eta_realtime_indicator);
    mEtaMoreVert2 = (ImageButton) mEtaContainer2.findViewById(R.id.eta_more_vert);
    mEtaMoreVert2.setColorFilter(mView.getResources().getColor(R.color.header_text_color));

    mProgressBar = (ProgressBar) mView.findViewById(R.id.header_loading_spinner);
    mStopInfo = (ImageButton) mView.findViewById(R.id.stop_info_button);
    mExpandCollapse = (ImageView) mView.findViewById(R.id.expand_collapse);
    mAlertView = (ImageView) mView.findViewById(R.id.alert);
    mAlertView.setColorFilter(mView.getResources().getColor(R.color.header_text_color));
    mAlertView.setVisibility(View.GONE);

    resetExpandCollapseAnimation();

    // Initialize right margin view visibilities
    UIUtils.showViewWithAnimation(mProgressBar, mShortAnimationDuration);

    UIUtils.hideViewWithAnimation(mEtaContainer1, mShortAnimationDuration);
    UIUtils.hideViewWithAnimation(mEtaSeparator, mShortAnimationDuration);
    UIUtils.hideViewWithAnimation(mEtaContainer2, mShortAnimationDuration);

    // Initialize stop info view
    final ObaRegion obaRegion = Application.get().getCurrentRegion();

    if (obaRegion == null || TextUtils.isEmpty(obaRegion.getStopInfoUrl())) {
        // This region doesn't support StopInfo - hide the info icon
        mStopInfo.setVisibility(View.GONE);
    } else {
        mStopInfo.setVisibility(View.VISIBLE);

        mStopInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Assemble StopInfo URL for the current stop
                Uri stopInfoUri = Uri.parse(obaRegion.getStopInfoUrl());
                Uri.Builder stopInfoBuilder = stopInfoUri.buildUpon();
                stopInfoBuilder.appendPath(mContext.getString(R.string.stop_info_url_path));
                stopInfoBuilder.appendPath(mController.getStopId());

                Log.d(TAG, "StopInfoUrl - " + stopInfoBuilder.build());

                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(stopInfoBuilder.build());
                mContext.startActivity(i);
                //Analytics
                if (obaRegion != null && obaRegion.getName() != null)
                    ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.UI_ACTION.toString(),
                            mContext.getString(R.string.analytics_action_button_press),
                            mContext.getString(R.string.analytics_label_button_press_stopinfo)
                                    + obaRegion.getName());
            }
        });
    }

    mStopFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mController.setFavoriteStop(!mController.isFavoriteStop());
            refreshStopFavorite();
        }
    });

    mNameView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            beginNameEdit(null);
        }
    });

    // Implement the "Save" and "Clear" buttons
    View save = mView.findViewById(R.id.edit_name_save);
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mController.setUserStopName(mEditNameView.getText().toString());
            endNameEdit();
        }
    });

    mEditNameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                mController.setUserStopName(mEditNameView.getText().toString());
                endNameEdit();
                return true;
            }
            return false;
        }
    });

    // "Cancel"
    View cancel = mView.findViewById(R.id.edit_name_cancel);
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            endNameEdit();
        }
    });

    View clear = mView.findViewById(R.id.edit_name_revert);
    clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mController.setUserStopName(null);
            endNameEdit();
        }
    });
}

From source file:io.github.hidroh.materialistic.data.HackerNewsItem.java

@NonNull
private SpannableString createAuthorSpannable(boolean authorLink) {
    SpannableString bySpannable = new SpannableString(AUTHOR_SEPARATOR + by);
    if (!authorLink) {
        return bySpannable;
    }//from w ww. j  a  v a  2  s .  co m
    bySpannable.setSpan(new StyleSpan(Typeface.BOLD), AUTHOR_SEPARATOR.length(), bySpannable.length(),
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            view.getContext()
                    .startActivity(new Intent(Intent.ACTION_VIEW).setData(AppUtils.createUserUri(getBy())));
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    bySpannable.setSpan(clickableSpan, AUTHOR_SEPARATOR.length(), bySpannable.length(),
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    return bySpannable;
}

From source file:org.mozilla.gecko.home.HistoryPanel.java

/**
 * Make Span that is clickable, italicized, and underlined
 * between the string markers <code>FORMAT_S1</code> and
 * <code>FORMAT_S2</code>./* w  ww  . j a  va  2 s .  c  o  m*/
 *
 * @param text String to format
 * @return formatted SpannableStringBuilder, or null if there
 * is not any text to format.
 */
private SpannableStringBuilder formatHintText(String text) {
    // Set formatting as marked by string placeholders.
    final int underlineStart = text.indexOf(FORMAT_S1);
    final int underlineEnd = text.indexOf(FORMAT_S2);

    // Check that there is text to be formatted.
    if (underlineStart >= underlineEnd) {
        return null;
    }

    final SpannableStringBuilder ssb = new SpannableStringBuilder(text);

    // Set italicization.
    ssb.setSpan(new StyleSpan(Typeface.ITALIC), 0, ssb.length(), 0);

    // Set clickable text.
    final ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Telemetry.sendUIEvent(TelemetryContract.Event.ACTION, TelemetryContract.Method.HOMESCREEN,
                    "hint-private-browsing");
            try {
                final JSONObject json = new JSONObject();
                json.put("type", "Menu:Open");
                EventDispatcher.getInstance().dispatchEvent(json, null);
            } catch (JSONException e) {
                Log.e(LOGTAG, "Error forming JSON for Private Browsing contextual hint", e);
            }
        }
    };

    ssb.setSpan(clickableSpan, 0, text.length(), 0);

    // Remove underlining set by ClickableSpan.
    final UnderlineSpan noUnderlineSpan = new UnderlineSpan() {
        @Override
        public void updateDrawState(TextPaint textPaint) {
            textPaint.setUnderlineText(false);
        }
    };

    ssb.setSpan(noUnderlineSpan, 0, text.length(), 0);

    // Add underlining for "Private Browsing".
    ssb.setSpan(new UnderlineSpan(), underlineStart, underlineEnd, 0);

    ssb.delete(underlineEnd, underlineEnd + FORMAT_S2.length());
    ssb.delete(underlineStart, underlineStart + FORMAT_S1.length());

    return ssb;
}

From source file:dev.drsoran.moloko.fragments.TaskFragment.java

private void setLocationSection(View view, final Task task) {
    String locationName = null;//from  w  w w  .jav  a  2  s.com

    boolean showSection = !TextUtils.isEmpty(task.getLocationId());

    if (showSection) {
        // Tasks which are received by sharing from someone else may also have
        // a location ID set. But this ID is from the other ones DB. We identify
        // these tasks not by looking for the ID in our DB. These tasks do not
        // have a name and a location of 0.0, 0.0.
        //
        // @see: Issue 12: http://code.google.com/p/moloko/issues/detail?id=12
        locationName = task.getLocationName();

        showSection = !TextUtils.isEmpty(locationName) || Float.compare(task.getLongitude(), 0.0f) != 0
                || Float.compare(task.getLatitude(), 0.0f) != 0;
    }

    if (!showSection) {
        view.setVisibility(View.GONE);
    } else {
        view.setVisibility(View.VISIBLE);

        if (TextUtils.isEmpty(locationName)) {
            locationName = "Lon: " + task.getLongitude() + ", Lat: " + task.getLatitude();
        }

        boolean locationIsClickable = task.isLocationViewable();

        if (locationIsClickable) {
            final SpannableString clickableLocation = new SpannableString(locationName);
            UIUtils.initializeTitleWithTextLayoutAsLink(view, getString(R.string.task_location),
                    clickableLocation, new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            listener.onOpenLocation(task);
                        }
                    });
        } else {
            UIUtils.initializeTitleWithTextLayout(view, getString(R.string.task_location), locationName);
        }
    }
}

From source file:dev.drsoran.moloko.fragments.TaskFragment.java

private void setParticipantsSection(ViewGroup view, Task task) {
    final ParticipantList participants = task.getParticipants();

    if (participants != null && participants.getCount() > 0) {
        view.setVisibility(View.VISIBLE);

        for (final Participant participant : participants.getParticipants()) {
            final TextView textView = new TextView(getSherlockActivity());
            UIUtils.makeLink(textView, participant.getFullname(), new ClickableSpan() {
                @Override/*from   ww  w .j  a va 2 s .c  o  m*/
                public void onClick(View widget) {
                    listener.onOpenContact(participant.getFullname(), participant.getUsername());
                }
            });

            view.addView(textView);
        }
    } else {
        view.setVisibility(View.GONE);
    }
}

From source file:com.kyakujin.android.tagnotepad.ui.NoteListFragment.java

/**
 * About/*from   w  ww  .j av a 2  s  .c o  m*/
 */
private void showAboutDialog() {
    PackageManager pm = getActivity().getPackageManager();
    String packageName = getActivity().getPackageName();
    String versionName;
    try {
        PackageInfo info = pm.getPackageInfo(packageName, 0);
        versionName = info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        versionName = "N/A";
    }

    SpannableStringBuilder aboutBody = new SpannableStringBuilder();

    SpannableString mailAddress = new SpannableString(getString(R.string.mailto));
    mailAddress.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse(getString(R.string.description_mailto)));
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.description_mail_subject));
            startActivity(intent);
        }
    }, 0, mailAddress.length(), 0);

    aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
    aboutBody.append("\n");
    aboutBody.append(mailAddress);

    LayoutInflater layoutInflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.fragment_about_dialog, null);
    aboutBodyView.setText(aboutBody);
    aboutBodyView.setMovementMethod(LinkMovementMethod.getInstance());

    AlertDialog dlg = new AlertDialog.Builder(getActivity()).setTitle(R.string.alert_title_about)
            .setView(aboutBodyView).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create();
    dlg.show();
}

From source file:com.kyakujin.android.autoeco.ui.MainActivity.java

/**
 * About/*from  w  w w  .  j  ava 2s  .  c o m*/
 */
private void showAboutDialog() {
    PackageManager pm = this.getPackageManager();
    String packageName = this.getPackageName();
    String versionName;
    try {
        PackageInfo info = pm.getPackageInfo(packageName, 0);
        versionName = info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        versionName = "N/A";
    }

    SpannableStringBuilder aboutBody = new SpannableStringBuilder();

    SpannableString mailAddress = new SpannableString(getString(R.string.mailto));
    mailAddress.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse(getString(R.string.description_mailto)));
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.description_mail_subject));
            startActivity(intent);
        }
    }, 0, mailAddress.length(), 0);

    aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
    aboutBody.append("\n");
    aboutBody.append(mailAddress);

    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.fragment_about_dialog, null);
    aboutBodyView.setText(aboutBody);
    aboutBodyView.setMovementMethod(LinkMovementMethod.getInstance());

    AlertDialog dlg = new AlertDialog.Builder(this).setTitle(R.string.alert_title_about).setView(aboutBodyView)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create();
    dlg.show();
}

From source file:ru.valle.btc.MainActivity.java

private void showQRCodePopupForAddress(final String address) {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    final int screenSize = Math.min(dm.widthPixels, dm.heightPixels);
    final String uriStr = SCHEME_BITCOIN + address;
    new AsyncTask<Void, Void, Bitmap>() {

        @Override// ww  w. ja v a  2 s  .co  m
        protected Bitmap doInBackground(Void... params) {
            return QRCode.getMinimumQRCode(uriStr, ErrorCorrectLevel.M).createImage(screenSize / 2);
        }

        @Override
        protected void onPostExecute(final Bitmap bitmap) {
            if (bitmap != null) {
                View view = getLayoutInflater().inflate(R.layout.address_qr, mainLayout, false);
                if (view != null) {
                    final ImageView qrView = (ImageView) view.findViewById(R.id.qr_code_image);
                    qrView.setImageBitmap(bitmap);

                    final TextView bitcoinProtocolLinkView = (TextView) view.findViewById(R.id.link1);
                    SpannableStringBuilder labelUri = new SpannableStringBuilder(uriStr);
                    ClickableSpan urlSpan = new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(uriStr));
                            try {
                                startActivity(intent);
                            } catch (Exception e) {
                                Toast.makeText(MainActivity.this, R.string.no_apps_to_view_url,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    };
                    labelUri.setSpan(urlSpan, 0, labelUri.length(),
                            SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                    bitcoinProtocolLinkView.setText(labelUri);
                    bitcoinProtocolLinkView.setMovementMethod(LinkMovementMethod.getInstance());

                    final TextView blockexplorerLinkView = (TextView) view.findViewById(R.id.link2);
                    SpannableStringBuilder blockexplorerLinkText = new SpannableStringBuilder(
                            "blockexplorer.com");
                    setUrlSpanForAddress("blockexplorer.com", address, blockexplorerLinkText);
                    blockexplorerLinkView.setText(blockexplorerLinkText);
                    blockexplorerLinkView.setMovementMethod(LinkMovementMethod.getInstance());

                    final TextView blockchainLinkView = (TextView) view.findViewById(R.id.link3);
                    SpannableStringBuilder blockchainLinkText = new SpannableStringBuilder("blockchain.info");
                    setUrlSpanForAddress("blockchain.info", address, blockchainLinkText);
                    blockchainLinkView.setText(blockchainLinkText);
                    blockchainLinkView.setMovementMethod(LinkMovementMethod.getInstance());

                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(address);
                    builder.setView(view);
                    if (systemSupportsPrint()) {
                        builder.setPositiveButton(R.string.print, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Renderer.printQR(MainActivity.this, SCHEME_BITCOIN + address);
                            }
                        });
                        builder.setNegativeButton(android.R.string.cancel, null);
                    } else {
                        builder.setPositiveButton(android.R.string.ok, null);
                    }

                    builder.show();
                }
            }
        }
    }.execute();
}

From source file:com.github.michalbednarski.intentslab.editor.IntentGeneralFragment.java

@Override
public void onTrackerUpdate() {
    IntentTracker tracker = getIntentEditor().getIntentTracker();
    FormattedTextBuilder ftb = new FormattedTextBuilder();
    ftb.appendRaw("[Tracking intent]\naction " + (tracker.actionRead() ? "" : "NOT ") + "read");
    ftb.appendText("Read extras:");
    for (final ReadBundleEntryInfo entryInfo : tracker.getExtrasTracker().getReadEntries()) {
        ftb.appendClickable(entryInfo.name, new ClickableSpan() {
            @Override/*from   w ww  .j a va  2  s. c o  m*/
            public void onClick(View widget) {
                String message = entryInfo.methodName;
                if (entryInfo.stackTrace != null) {
                    message += "\n\n";
                    for (StackTraceElement element : entryInfo.stackTrace) {
                        message += element.getClassName() + " " + element.getMethodName() + " "
                                + element.getLineNumber() + "\n";
                    }
                }
                new AlertDialog.Builder(getActivity()).setTitle(entryInfo.name).setMessage(message).show();
            }
        });
    }
    mIntentTrackerSummary.setText(ftb.getText());
    mIntentTrackerSummary.setVisibility(View.VISIBLE);
}

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

private static CharSequence getLinkSpan(final AstridActivity activity, UserActivity update, String targetName,
        String linkColor, String linkType) {
    if (TASK_LINK_TYPE.equals(linkType)) {
        final String taskId = update.getValue(UserActivity.TARGET_ID);
        if (RemoteModel.isValidUuid(taskId)) {
            SpannableString taskSpan = new SpannableString(targetName);
            taskSpan.setSpan(new ClickableSpan() {
                @Override//from   w w  w. jav  a 2  s.  co m
                public void onClick(View widget) {
                    if (activity != null) // TODO: This shouldn't happen, but sometimes does
                        activity.onTaskListItemClicked(taskId);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                }
            }, 0, targetName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            return taskSpan;
        } else {
            return Html.fromHtml(linkify(targetName, linkColor));
        }
    }
    return null;
}