Example usage for android.text SpannableString setSpan

List of usage examples for android.text SpannableString setSpan

Introduction

In this page you can find the example usage for android.text SpannableString setSpan.

Prototype

public void setSpan(Object what, int start, int end, int flags) 

Source Link

Usage

From source file:android.support.v7.widget.SuggestionsAdapter.java

private CharSequence formatUrl(CharSequence url) {
    if (mUrlColor == null) {
        // Lazily get the URL color from the current theme.
        TypedValue colorValue = new TypedValue();
        mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl, colorValue, true);
        mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId);
    }/*  w w  w.j a v a 2  s  .  c om*/

    SpannableString text = new SpannableString(url);
    text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null), 0, url.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return text;
}

From source file:com.techno.jay.codingcontests.Home.java

private void applyFontToMenuItem(MenuItem mi) {
    Typeface font = Typeface.createFromAsset(getAssets(), "ProductSans-Regular.ttf");
    SpannableString mNewTitle = new SpannableString(mi.getTitle());
    mNewTitle.setSpan(new CustomTypefaceSpan("", font), 0, mNewTitle.length(),
            Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    mi.setTitle(mNewTitle);/* w  ww.  ja v  a 2  s .  c  o  m*/
}

From source file:android.support.v7ox.widget.SuggestionsAdapter.java

private CharSequence formatUrl(CharSequence url) {
    if (mUrlColor == null) {
        // Lazily get the URL color from the current theme.
        TypedValue colorValue = new TypedValue();
        mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl_ox, colorValue, true);
        mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId);
    }/*from   w  ww  . j  a  v  a  2s.c  o m*/

    SpannableString text = new SpannableString(url);
    text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null), 0, url.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return text;
}

From source file:com.evandroid.musica.fragment.LyricsViewFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setRetainInstance(true);//from   w  w w .  j  ava 2  s  . c  om
    setHasOptionsMenu(true);
    View layout = inflater.inflate(R.layout.lyrics_view, container, false);
    if (savedInstanceState != null)
        try {
            Lyrics l = Lyrics.fromBytes(savedInstanceState.getByteArray("lyrics"));
            if (l != null)
                this.mLyrics = l;
            mSearchQuery = savedInstanceState.getString("searchQuery");
            mSearchFocused = savedInstanceState.getBoolean("searchFocused");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    else {
        Bundle args = getArguments();
        if (args != null)
            try {
                Lyrics lyrics = Lyrics.fromBytes(args.getByteArray("lyrics"));
                this.mLyrics = lyrics;
                if (lyrics != null && lyrics.getText() == null && lyrics.getArtist() != null) {
                    String artist = lyrics.getArtist();
                    String track = lyrics.getTrack();
                    String url = lyrics.getURL();
                    fetchLyrics(artist, track, url);
                    mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout);
                    startRefreshAnimation();
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
    }
    if (layout != null) {
        Bundle args = savedInstanceState != null ? savedInstanceState : getArguments();

        boolean screenOn = PreferenceManager.getDefaultSharedPreferences(getActivity())
                .getBoolean("pref_force_screen_on", false);

        TextSwitcher textSwitcher = (TextSwitcher) layout.findViewById(R.id.switcher);
        textSwitcher.setFactory(new LyricsTextFactory(layout.getContext()));
        ActionMode.Callback callback = new CustomSelectionCallback(getActivity());
        ((TextView) textSwitcher.getChildAt(0)).setCustomSelectionActionModeCallback(callback);
        ((TextView) textSwitcher.getChildAt(1)).setCustomSelectionActionModeCallback(callback);
        textSwitcher.setKeepScreenOn(screenOn);
        layout.findViewById(R.id.lrc_view).setKeepScreenOn(screenOn);

        TextView id3TV = (TextView) layout.findViewById(R.id.id3_tv);
        SpannableString text = new SpannableString(id3TV.getText());
        text.setSpan(new UnderlineSpan(), 1, text.length() - 1, 0);
        id3TV.setText(text);

        final RefreshIcon refreshFab = (RefreshIcon) getActivity().findViewById(R.id.refresh_fab);
        refreshFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mRefreshLayout.isRefreshing())
                    fetchCurrentLyrics(true);
            }
        });

        FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class);
                startActivity(settingsIntent);
            }
        });

        if (args != null)
            refreshFab.setEnabled(args.getBoolean("refreshFabEnabled", true));

        mScrollView = (NestedScrollView) layout.findViewById(R.id.scrollview);
        mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout);
        TypedValue primaryColor = new TypedValue();
        getActivity().getTheme().resolveAttribute(R.attr.colorPrimary, primaryColor, true);
        mRefreshLayout.setColorSchemeResources(primaryColor.resourceId, R.color.accent);
        float offset = getResources().getDisplayMetrics().density * 64;
        mRefreshLayout.setProgressViewEndTarget(true, (int) offset);
        mRefreshLayout.setOnRefreshListener(this);

        if (mLyrics == null) {
            if (!startEmtpy)
                fetchCurrentLyrics(false);
        } else if (mLyrics.getFlag() == Lyrics.SEARCH_ITEM) {
            mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout);
            startRefreshAnimation();
            if (mLyrics.getArtist() != null)
                fetchLyrics(mLyrics.getArtist(), mLyrics.getTrack());
        } else //Rotation, resume
            update(mLyrics, layout, false);
    }
    if (broadcastReceiver == null)
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                searchResultLock = false;
                String artist = intent.getStringExtra("artist");
                String track = intent.getStringExtra("track");
                if (artist != null && track != null && mRefreshLayout.isEnabled()) {
                    startRefreshAnimation();
                    new ParseTask(LyricsViewFragment.this, false, true).execute(mLyrics);
                }
            }
        };
    return layout;
}

From source file:org.catrobat.catroid.ui.MainMenuActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main_menu, menu);
    mainMenu = menu;//  w  w w .  j a v a2  s .  c om

    final MenuItem scratchConverterMenuItem = menu.findItem(R.id.menu_scratch_converter);
    if (scratchConverterMenuItem != null) {
        final String title = getString(R.string.main_menu_scratch_converter);
        final String beta = getString(R.string.beta).toUpperCase(Locale.getDefault());
        final SpannableString spanTitle = new SpannableString(title + " " + beta);
        final int begin = title.length() + 1;
        final int end = begin + beta.length();
        final int betaLabelColor = ContextCompat.getColor(this, R.color.beta_label_color);
        spanTitle.setSpan(new ForegroundColorSpan(betaLabelColor), begin, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        scratchConverterMenuItem.setTitle(spanTitle);
    }
    return super.onCreateOptionsMenu(menu);
}

From source file:com.barbrdo.app.activities.UserProfileActivity.java

@Override
void bindControls() {
    editTextPhone.addTextChangedListener(new PhoneNumberFormattingTextWatcher(editTextPhone));
    imageViewProfilePicture.setOnClickListener(this);
    textViewSearchRadius.setOnClickListener(this);
    textViewChangePassword.setOnClickListener(this);
    SpannableString content = new SpannableString(getString(R.string.change_password));
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    textViewChangePassword.setText(content);

    getView(R.id.cv_password_change).setVisibility(View.GONE);
    textViewCancel.setOnClickListener(this);
    textViewUpgrade.setOnClickListener(this);
}

From source file:fr.cph.chicago.core.adapter.FavoritesAdapter.java

private void handleBusRoute(@NonNull final FavoritesViewHolder holder, @NonNull final BusRoute busRoute) {
    holder.stationNameTextView.setText(busRoute.getId());
    holder.favoriteImage.setImageResource(R.drawable.ic_directions_bus_white_24dp);

    final List<BusDetailsDTO> busDetailsDTOs = new ArrayList<>();

    final Map<String, Map<String, List<BusArrival>>> busArrivals = favoritesData
            .getBusArrivalsMapped(busRoute.getId());
    for (final Entry<String, Map<String, List<BusArrival>>> entry : busArrivals.entrySet()) {
        // Build data for button outside of the loop
        final String stopName = entry.getKey();
        final String stopNameTrimmed = Util.trimBusStopNameIfNeeded(stopName);
        final Map<String, List<BusArrival>> value = entry.getValue();
        for (final String key2 : value.keySet()) {
            final BusArrival busArrival = value.get(key2).get(0);
            final String boundTitle = busArrival.getRouteDirection();
            final BusDirection.BusDirectionEnum busDirectionEnum = BusDirection.BusDirectionEnum
                    .fromString(boundTitle);
            final BusDetailsDTO busDetails = BusDetailsDTO.builder().busRouteId(busArrival.getRouteId())
                    .bound(busDirectionEnum.getShortUpperCase()).boundTitle(boundTitle)
                    .stopId(Integer.toString(busArrival.getStopId())).routeName(busRoute.getName())
                    .stopName(stopName).build();
            busDetailsDTOs.add(busDetails);
        }/*from w ww  .j a  v  a  2 s. com*/

        boolean newLine = true;
        int i = 0;

        for (final Entry<String, List<BusArrival>> entry2 : value.entrySet()) {
            final LinearLayout.LayoutParams containParams = getInsideParams(newLine, i == value.size() - 1);
            final LinearLayout container = new LinearLayout(context);
            container.setOrientation(LinearLayout.HORIZONTAL);
            container.setLayoutParams(containParams);

            // Left
            final LinearLayout.LayoutParams leftParams = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            final RelativeLayout left = new RelativeLayout(context);
            left.setLayoutParams(leftParams);

            final RelativeLayout lineIndication = LayoutUtil.createColoredRoundForFavorites(context,
                    TrainLine.NA);
            int lineId = Util.generateViewId();
            lineIndication.setId(lineId);

            final RelativeLayout.LayoutParams destinationParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            destinationParams.addRule(RelativeLayout.RIGHT_OF, lineId);
            destinationParams.setMargins(pixelsHalf, 0, 0, 0);

            final String bound = BusDirection.BusDirectionEnum.fromString(entry2.getKey()).getShortLowerCase();
            final String leftString = stopNameTrimmed + " " + bound;
            final SpannableString destinationSpannable = new SpannableString(leftString);
            destinationSpannable.setSpan(new RelativeSizeSpan(0.65f), stopNameTrimmed.length(),
                    leftString.length(), 0); // set size
            destinationSpannable.setSpan(new ForegroundColorSpan(grey5), 0, leftString.length(), 0); // set color

            final TextView boundCustomTextView = new TextView(context);
            boundCustomTextView.setText(destinationSpannable);
            boundCustomTextView.setSingleLine(true);
            boundCustomTextView.setLayoutParams(destinationParams);

            left.addView(lineIndication);
            left.addView(boundCustomTextView);

            // Right
            final LinearLayout.LayoutParams rightParams = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            rightParams.setMargins(marginLeftPixel, 0, 0, 0);
            final LinearLayout right = new LinearLayout(context);
            right.setOrientation(LinearLayout.VERTICAL);
            right.setLayoutParams(rightParams);

            final List<BusArrival> buses = entry2.getValue();
            final StringBuilder currentEtas = new StringBuilder();
            for (final BusArrival arri : buses) {
                currentEtas.append(" ").append(arri.getTimeLeftDueDelay());
            }
            final TextView arrivalText = new TextView(context);
            arrivalText.setText(currentEtas);
            arrivalText.setGravity(Gravity.END);
            arrivalText.setSingleLine(true);
            arrivalText.setTextColor(grey5);
            arrivalText.setEllipsize(TextUtils.TruncateAt.END);

            right.addView(arrivalText);

            container.addView(left);
            container.addView(right);

            holder.mainLayout.addView(container);

            newLine = false;
            i++;
        }
    }

    holder.mapButton.setText(activity.getString(R.string.favorites_view_buses));
    holder.detailsButton
            .setOnClickListener(new BusStopOnClickListener(activity, holder.parent, busDetailsDTOs));
    holder.mapButton.setOnClickListener(v -> {
        if (!Util.isNetworkAvailable(context)) {
            Util.showNetworkErrorMessage(activity);
        } else {
            final Set<String> bounds = Stream.of(busDetailsDTOs).map(BusDetailsDTO::getBound)
                    .collect(Collectors.toSet());
            final Intent intent = new Intent(activity.getApplicationContext(), BusMapActivity.class);
            final Bundle extras = new Bundle();
            extras.putString(activity.getString(R.string.bundle_bus_route_id), busRoute.getId());
            extras.putStringArray(activity.getString(R.string.bundle_bus_bounds),
                    bounds.toArray(new String[bounds.size()]));
            intent.putExtras(extras);
            activity.startActivity(intent);
        }
    });
}

From source file:com.android.mail.browse.ConversationItemView.java

private static SpannableString copyStyles(CharacterStyle[] spans, CharSequence newText) {
    SpannableString s = new SpannableString(newText);
    if (spans != null && spans.length > 0) {
        s.setSpan(spans[0], 0, s.length(), 0);
    }//from  www.ja v  a  2s .  c om
    return s;
}

From source file:se.anyro.tagtider.TransferActivity.java

private void setupTransferData(final Bundle extras) {
    TextView trainView = (TextView) findViewById(R.id.train);

    ViewGroup originGroup = (ViewGroup) findViewById(R.id.origin_group);
    TextView originView = (TextView) findViewById(R.id.origin);
    TextView arrivalView = (TextView) findViewById(R.id.arrival);

    TextView stationTrackView = (TextView) findViewById(R.id.station_track);

    ViewGroup destinationGroup = (ViewGroup) findViewById(R.id.destination_group);
    TextView destinationView = (TextView) findViewById(R.id.destination);
    TextView departureView = (TextView) findViewById(R.id.departure);

    TextView commentView = (TextView) findViewById(R.id.comment);
    mEmptyView = (TextView) findViewById(android.R.id.empty);

    trainView.setText("Tg " + extras.getString("train") + " (" + extras.getString("type") + ")");

    String origin = extras.getString("origin");
    if (origin != null && origin.length() > 0) {
        originView.setText("Frn " + origin);
        originGroup.setVisibility(View.VISIBLE);
    } else {//from  w  w  w . jav  a2  s .  c om
        originGroup.setVisibility(View.GONE);
    }

    String track = extras.getString("track");
    if (track == null || track.equalsIgnoreCase("x") || track.equalsIgnoreCase("null"))
        track = "";

    String arrival = extras.getString("arrival");
    if (arrival != null && !arrival.startsWith("0000")) {
        arrivalView.setText("Ankommer " + StringUtils.extractTime(arrival));
        String newArrival = extras.getString("newArrival");
        if (newArrival != null) {
            newArrival = StringUtils.extractTime(newArrival);
            SpannableString strike = new SpannableString(arrivalView.getText() + " " + newArrival);
            strike.setSpan(new StrikethroughSpan(), strike.length() - 11, strike.length() - 6, 0);
            arrivalView.setText(strike, TextView.BufferType.SPANNABLE);
        }
        if (track.length() == 0) {
            SpannableString strike = new SpannableString(arrivalView.getText());
            strike.setSpan(new StrikethroughSpan(), strike.length() - 5, strike.length(), 0);
            arrivalView.setText(strike, TextView.BufferType.SPANNABLE);
        }
    }

    if (extras.getString("stationName") != null) {
        mStationName = extras.getString("stationName");
    }

    if (track.length() > 0 && mStationName != null)
        stationTrackView.setText(mStationName + ", spr " + track);
    else if (mStationName != null)
        stationTrackView.setText(mStationName);
    else if (track.length() > 0)
        stationTrackView.setText("Spr " + track);
    else
        stationTrackView.setText("");

    String destination = extras.getString("destination");
    if (destination != null && destination.length() > 0) {
        destinationView.setText("Till " + destination);
        destinationGroup.setVisibility(View.VISIBLE);
    } else {
        destinationGroup.setVisibility(View.GONE);
    }

    String departure = extras.getString("departure");
    if (departure != null && !departure.startsWith("0000")) {
        departureView.setText("Avgr " + StringUtils.extractTime(departure));
        String newDeparture = extras.getString("newDeparture");
        if (newDeparture != null) {
            newDeparture = StringUtils.extractTime(newDeparture);
            SpannableString strike = new SpannableString(departureView.getText() + " " + newDeparture);
            strike.setSpan(new StrikethroughSpan(), strike.length() - 11, strike.length() - 6, 0);
            departureView.setText(strike, TextView.BufferType.SPANNABLE);
        }
        if (track.length() == 0) {
            SpannableString strike = new SpannableString(departureView.getText());
            strike.setSpan(new StrikethroughSpan(), strike.length() - 5, strike.length(), 0);
            departureView.setText(strike, TextView.BufferType.SPANNABLE);
        }
    }

    String comment = extras.getString("comment");
    if ((comment == null || comment.length() == 0) && track.length() == 0)
        comment = "Instllt";
    if (comment != null && comment.length() > 0) {
        commentView.setText(comment);
        commentView.setVisibility(View.VISIBLE);
    } else {
        commentView.setVisibility(View.GONE);
    }

    mTrain = extras.getString("train");
    mStationId = extras.getString("stationId");

    mTransferId = extras.getString("id");
}

From source file:com.kawakawaplanning.rssreader.Main.MainActivity.java

private SpannableString createSpannableString(String message, Map<String, String> map) {

    SpannableString ss = new SpannableString(message);

    for (final Map.Entry<String, String> entry : map.entrySet()) {
        int start = 0;
        int end = 0;

        // ?? start, end ?
        Pattern pattern = Pattern.compile(entry.getKey());
        Matcher matcher = pattern.matcher(message);
        while (matcher.find()) {
            start = matcher.start();//from www  .  ja  v a 2s. c  om
            end = matcher.end();
            break;
        }

        // SpannableString ???
        ss.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                Intent intent = new Intent(getApplicationContext(), OpenSourceLicenseActivity.class);
                startActivity(intent);
            }
        }, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }

    return ss;
}