Example usage for android.text.style RelativeSizeSpan RelativeSizeSpan

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

Introduction

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

Prototype

public RelativeSizeSpan(@NonNull Parcel src) 

Source Link

Document

Creates a RelativeSizeSpan from a parcel.

Usage

From source file:at.jclehner.rxdroid.SplashScreenActivity.java

@TargetApi(11)
@Override//from  w  w  w .  jav  a  2  s.co m
protected void onCreate(Bundle savedInstanceState) {
    Settings.init();

    setTheme(Theme.get());
    setContentView(R.layout.loader);

    mDate = Settings.getActiveDate();

    final SpannableString dateString = new SpannableString(DateTime.toNativeDate(mDate));

    Util.applyStyle(dateString, new RelativeSizeSpan(0.75f));
    Util.applyStyle(dateString, new UnderlineSpan());

    getSupportActionBar().setSubtitle(dateString);

    try {
        Class.forName(com.michaelnovakjr.numberpicker.NumberPicker.class.getName());
    } catch (ClassNotFoundException e) {
        throw new WrappedCheckedException("NumberPicker library is missing", e);
    }

    super.onCreate(savedInstanceState);
}

From source file:com.saulmm.cui.OrderDialogFragment.java

@BindingAdapter("app:spanOffset")
public static void setItemSpan(View v, int spanOffset) {
    final String itemText = ((TextView) v).getText().toString();
    final SpannableString sString = new SpannableString(itemText);

    sString.setSpan(new RelativeSizeSpan(1.65f), itemText.length() - spanOffset, itemText.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    ((TextView) v).setText(sString);/*w w w .  ja  va 2  s  .c om*/
}

From source file:com.softminds.matrixcalculator.base_activities.FillingMatrix.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isDark = preferences.getBoolean("DARK_THEME_KEY", false);
    boolean SmartFit = preferences.getBoolean("SMART_FIT_KEY", false);

    if (isDark)//from w w  w  . j  a  v a 2 s .  co m
        setTheme(R.style.AppThemeDark_NoActionBar);
    else
        setTheme(R.style.AppTheme_NoActionBar);
    super.onCreate(savedInstanceState);

    Bundle bundle = getIntent().getExtras();
    if (bundle == null) {
        Log.wtf("FillingMatrix", "How the heck, it got called ??");
        Toast.makeText(getApplication(), R.string.unexpected_error, Toast.LENGTH_SHORT).show();
        finish();
    } else {
        col = bundle.getInt("COL");
        row = bundle.getInt("ROW");
    }
    setContentView(R.layout.filler);
    adCard = findViewById(R.id.AddCardFiller);

    if (!((GlobalValues) getApplication()).DonationKeyFound()) {
        AdView adView = findViewById(R.id.adViewFiller);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.setAdListener(new AdLoadListener(adCard));
        adView.loadAd(adRequest);
        if (getResources()
                .getConfiguration().orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE)
            adCard.setVisibility(View.INVISIBLE);
        else
            adCard.setVisibility(View.VISIBLE);
    } else
        ((ViewGroup) adCard.getParent()).removeView(adCard);

    Toolbar toolbar = findViewById(R.id.toolbarFill);
    setSupportActionBar(toolbar);

    CardView cardView = findViewById(R.id.DynamicCard);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String string = sharedPreferences.getString("ELEVATE_AMOUNT", "4");
    String string2 = sharedPreferences.getString("CARD_CHANGE_KEY", "#bdbdbd");

    cardView.setCardElevation(Integer.parseInt(string));

    CardView.LayoutParams params1 = new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    GridLayout gridLayout = new GridLayout(getApplicationContext());
    gridLayout.setRowCount(row);
    gridLayout.setColumnCount(col);
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            EditText editText = new EditText(getApplication());
            editText.setBackgroundColor(Color.parseColor(string2));
            editText.setId(i * 10 + j);
            if (isDark)
                editText.setTextColor(ContextCompat.getColor(this, R.color.white));
            editText.setGravity(Gravity.CENTER);
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder(
                    "a" + String.valueOf(i + 1) + String.valueOf(j + 1));
            stringBuilder.setSpan(new SubscriptSpan(), 1, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            stringBuilder.setSpan(new RelativeSizeSpan(0.75f), 1, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            editText.setHint(stringBuilder);
            if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("DECIMAL_USE", true)) {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
            } else {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                        | InputType.TYPE_NUMBER_FLAG_SIGNED);
            }
            editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(getLength()) });
            if (SmartFit) {
                editText.setWidth(ConvertTopx(CalculatedWidth(col)));
                editText.setTextSize(SizeReturner(row, col,
                        PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                                .getBoolean("EXTRA_SMALL_FONT", false)));
            } else {
                editText.setWidth(ConvertTopx(62));
                editText.setTextSize(SizeReturner(3, 3,
                        PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                                .getBoolean("EXTRA_SMALL_FONT", false)));
            }
            editText.setSingleLine();
            GridLayout.Spec Row = GridLayout.spec(i, 1);
            GridLayout.Spec Col = GridLayout.spec(j, 1);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(Row, Col);
            params.leftMargin = params.topMargin = params.bottomMargin = params.rightMargin = getResources()
                    .getDimensionPixelOffset(R.dimen.border_width);
            gridLayout.addView(editText, params);
        }
    }
    gridLayout.setLayoutParams(params1);
    cardView.addView(gridLayout);
    MakeType((Type) (getIntent().getExtras().getSerializable("TYPE")));
    if (GetMaximum() < GetMinimum()) {
        final Snackbar snackbar;
        snackbar = Snackbar.make(findViewById(R.id.filling_matrix), R.string.Warning3,
                Snackbar.LENGTH_INDEFINITE);
        snackbar.show();
        snackbar.setAction(getString(R.string.action_settings), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                snackbar.dismiss();
                Intent intent = new Intent(getApplicationContext(), SettingsTab.class);
                startActivity(intent);
                finish();
            }
        });
    }

}

From source file:com.android.purenexussettings.TinkerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tinker);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*w ww  .j ava2  s  .co  m*/

    // set up some defaults
    boolean cLockInstalled;
    FRAG_ARRAY_START = getResources().getIntArray(R.array.nav_drawer_cat_nums)[0];
    mTitle = mDrawerTitle = getTitle();
    mPackageName = getPackageName();
    LAST_SLIDE_BAR_TAB = 0;
    mBackPress = false;
    mIgnoreBack = false;
    mFromClick = false;
    mMenu = false;
    fullyClosed = true;
    openingHalf = true;

    // for backstack tracking
    fragmentStack = new Stack<>();

    // check if cLock installed
    try {
        PackageInfo pi = getPackageManager().getPackageInfo(KEY_LOCK_CLOCK_PACKAGE_NAME, 0);
        cLockInstalled = pi.applicationInfo.enabled;
    } catch (PackageManager.NameNotFoundException e) {
        cLockInstalled = false;
    }

    // load slide menu items - titles and frag names
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    navMenuFrags = getResources().getStringArray(R.array.nav_drawer_fragments);

    // nav drawer icons from resources
    TypedArray navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    mNavView = (NavigationView) findViewById(R.id.slidermenu);

    // create navigationview items
    Menu menu = mNavView.getMenu();
    // pulled in crap menu in xml, need to clear it first
    menu.clear();

    // pull in category names and numbers in each
    String[] navMenuCats = getResources().getStringArray(R.array.nav_drawer_cats);
    int[] navMenuCatCounts = getResources().getIntArray(R.array.nav_drawer_cat_nums);

    // set up some counters
    int j = 0;
    int total = 0;
    SubMenu submenu = null;
    // go through the total possible menu list
    for (int i = 0; i < navMenuTitles.length; i++) {
        // when the count equals a threshold value, increment/sum and add submenu
        if (i == (total + navMenuCatCounts[j])) {
            total += navMenuCatCounts[j];
            // format submenu headings
            SpannableString strcat = new SpannableString(navMenuCats[j]);
            strcat.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.alphawhite)), 0,
                    strcat.length(), 0);
            strcat.setSpan(new RelativeSizeSpan(0.85f), 0, strcat.length(), 0);
            strcat.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, strcat.length(), 0);
            // is the 10 * (j + 1) bit needed...? Maybe not... meh
            submenu = menu.addSubMenu((j + 1), 10 * (j + 1), 10 * (j + 1), strcat);
            j++;
        }
        // assuming all are skipped before first submenu, only add menu items if total <> 0
        if (total > 0) {
            // format menu item title
            SpannableString stritem = new SpannableString(navMenuTitles[i]);
            stritem.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.alphawhite)), 0,
                    stritem.length(), 0);
            // group id is j, i is item id and order..., then title - includes logic for conditional entries
            if (cLockInstalled || !(navMenuTitles[i].equals("cLock"))) {
                // an attempt to add icon if included...
                if (navMenuIcons.getResourceId(i, -1) != -1) {
                    submenu.add(j, i, i, stritem).setIcon(navMenuIcons.getResourceId(i, -1));
                } else {
                    submenu.add(j, i, i, stritem);
                }
            }
        }
    }

    // remove icon tint from NavView
    mNavView.setItemIconTintList(null);

    mNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            // check for external app launching navdrawer items
            if (navMenuTitles[item.getItemId()].equals("cLock")) {
                mIgnore = true;
                mDrawerLayout.closeDrawer(mNavView);
                launchcLock();
            }

            // if nothing was caught in the above, do the usual prep to show frag stuff
            if (!mIgnore) {
                mItemPosition = item.getItemId();
                mFromClick = true;
                setTitle(navMenuTitles[mItemPosition]);
                removeCurrent();
                mDrawerLayout.closeDrawer(mNavView);
            }

            return true;
        }
    });

    // Recycle the typed array
    navMenuIcons.recycle();

    // enabling action bar app icon and behaving it as toggle button
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, //nav menu toggle icon
            R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        @Override
        public void onDrawerClosed(View view) {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mNavView);
            getSupportActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            openingHalf = true;
            invalidateOptionsMenu();
            // now that the drawer animation is done - load fragment
            if (mIgnore || !mFromClick) {
                mIgnore = false;
            } else {
                displayView(mItemPosition);
            }
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            openingHalf = false;
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            fullyClosed = (slideOffset == 0.0f);
            if (slideOffset < 0.5f && !openingHalf) {
                openingHalf = true;
                invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            } else if (slideOffset > 0.5f && openingHalf) {
                openingHalf = false;
                invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        }

    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    fragmentManager = getFragmentManager();

    if (savedInstanceState == null) {
        // on first time display view for first nav item
        displayView(mItemPosition = getIntent().getIntExtra(EXTRA_START_FRAGMENT, 0));
    }
}

From source file:org.thoughtcrime.securesms.PassphrasePromptActivity.java

private void initializeResources() {

    ImageButton okButton = findViewById(R.id.ok_button);
    Toolbar toolbar = findViewById(R.id.toolbar);

    showButton = findViewById(R.id.passphrase_visibility);
    hideButton = findViewById(R.id.passphrase_visibility_off);
    visibilityToggle = findViewById(R.id.button_toggle);
    passphraseText = findViewById(R.id.passphrase_edit);
    passphraseAuthContainer = findViewById(R.id.password_auth_container);
    fingerprintPrompt = findViewById(R.id.fingerprint_auth_container);
    lockScreenButton = findViewById(R.id.lock_screen_auth_container);
    fingerprintManager = FingerprintManagerCompat.from(this);
    fingerprintCancellationSignal = new CancellationSignal();
    fingerprintListener = new FingerprintListener();

    setSupportActionBar(toolbar);/*from   w  ww.ja  v  a2s.c om*/
    getSupportActionBar().setTitle("");

    SpannableString hint = new SpannableString(
            "  " + getString(R.string.PassphrasePromptActivity_enter_passphrase));
    hint.setSpan(new RelativeSizeSpan(0.9f), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    hint.setSpan(new TypefaceSpan("sans-serif"), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

    passphraseText.setHint(hint);
    okButton.setOnClickListener(new OkButtonClickListener());
    showButton.setOnClickListener(new ShowButtonOnClickListener());
    hideButton.setOnClickListener(new HideButtonOnClickListener());
    passphraseText.setOnEditorActionListener(new PassphraseActionListener());
    passphraseText.setImeActionLabel(getString(R.string.prompt_passphrase_activity__unlock),
            EditorInfo.IME_ACTION_DONE);

    fingerprintPrompt.setImageResource(R.drawable.ic_fingerprint_white_48dp);
    fingerprintPrompt.getBackground().setColorFilter(getResources().getColor(R.color.signal_primary),
            PorterDuff.Mode.SRC_IN);

    lockScreenButton.setOnClickListener(v -> resumeScreenLock());
}

From source file:com.groksolutions.grok.mobile.annotation.AnnotationListFragment.java

/**
 * Format annotation message footer for list item display
 *
 * @param annotation//www . j a  v a 2 s  .  c o m
 * @param showDate
 * @return
 */
SpannableStringBuilder formatAnnotationFooter(Annotation annotation, boolean showDate) {
    int pos, rightPos;

    Date created = new Date(annotation.getCreated());
    // Format text
    SpannableStringBuilder text = new SpannableStringBuilder();

    // <div align="right">
    rightPos = pos = text.length();

    //<small>6/30/14 3:25 PM - </small>

    // Show date if different annotation or if created date changed
    if (showDate) {
        text.append(_dateFormat.format(created)).append(" ");
    }
    text.append(_timeFormat.format(created)).append(" - ");
    text.setSpan(new RelativeSizeSpan(0.5f), pos, text.length(), 0);

    // User
    pos = text.length();
    text.append(annotation.getUser());
    text.setSpan(new RelativeSizeSpan(1.0f), pos, text.length(), 0);

    // </div align="right">
    text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE), rightPos, text.length(), 0);

    // Attach hidden annotation ID to the text.
    // This ID is used by the actions attached to the list
    text.setSpan(new android.text.Annotation("id", annotation.getId()), 0, text.length(), 0);

    return text;
}

From source file:com.ideascontest.navi.uask.MainQuestionAnswerAdapter.java

/**
 * OnBindViewHolder is called by the RecyclerView to display the data at the specified
 * position. In this method, we update the contents of the ViewHolder to display the correct
 * indices in the list for this particular position, using the "position" argument that is conveniently
 * passed into us./*www . j  av  a 2  s .c  o m*/
 *
 * @param holder   The ViewHolder which should be updated to represent the contents of the
 *                 item at the given position in the data set.
 * @param position The position of the item within the adapter's data set.
 */
@Override
public void onBindViewHolder(QuestionTopAnswerHolder holder, int position) {

    Log.d(TAG, "#" + position);
    QuestionTopAnswerHolder questionTopAnswerHolder = (QuestionTopAnswerHolder) holder;
    final Context context = questionTopAnswerHolder.v.getContext();
    Log.d(TAG, "Category" + _category);
    switch (_category) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4: {
        if (position == 0) {
            /*  String infoText = (String) questionTopAnswerHolder.basicInfoText.getText();
              int count = infoText.split("\n").length;
              int upperLimit = (count > 5) ? MainAnswerAdapter.ordinalIndexOf(infoText, "\n", 5) : 140;
              if (infoText.length() > 140 || count > 5) {
                  infoText = infoText.substring(0, upperLimit) + "... " + "view more";
                    
                  SpannableString sText = new SpannableString(infoText);
                  ClickableSpan myClickableSpan = new ClickableSpan() {
                      @Override
                      public void onClick(View v) {
                          Log.d("MainCanvas Category", "clickable Span");
                          //finish();
                      }
                  };
                  int spanLowLimit = upperLimit + 4;
                  int spanHighLimit = upperLimit + 13;
                  sText.setSpan(myClickableSpan, spanLowLimit, spanHighLimit, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                  sText.setSpan(new RelativeSizeSpan(0.75f), spanLowLimit, spanHighLimit, 0);
                  sText.setSpan(new ForegroundColorSpan( questionTopAnswerHolder.v.getResources().getColor(R.color.primaryOrange)), spanLowLimit, spanHighLimit, 0);
                  questionTopAnswerHolder.basicInfoText.setText(sText);
                  questionTopAnswerHolder.basicInfoText.setMovementMethod(LinkMovementMethod.getInstance());
              }*/
            String infoText = (String) questionTopAnswerHolder.basicInfoText.getText();
            int upperLimit = 150;
            if (infoText.length() > 150) {
                infoText = infoText.substring(0, upperLimit) + "... " + "view more";

                SpannableString sText = new SpannableString(infoText);
                ClickableSpan myClickableSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View v) {
                        Log.d("Mainadapter Category", "clickable Span");
                        Intent intent = new Intent(context, ShowBasicInfo.class);
                        intent.putExtra("category", _category);
                        context.startActivity(intent);//finish();
                    }
                };
                int spanLowLimit = upperLimit + 4;
                int spanHighLimit = upperLimit + 13;
                sText.setSpan(myClickableSpan, spanLowLimit, spanHighLimit, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                sText.setSpan(new RelativeSizeSpan(0.75f), spanLowLimit, spanHighLimit, 0);
                sText.setSpan(
                        new ForegroundColorSpan(
                                questionTopAnswerHolder.v.getResources().getColor(R.color.primaryOrange)),
                        spanLowLimit, spanHighLimit, 0);
                questionTopAnswerHolder.basicInfoText.setText(sText);
                questionTopAnswerHolder.basicInfoText.setMovementMethod(LinkMovementMethod.getInstance());
            }

        } else {
            populateDynamicUiElements(questionTopAnswerHolder, (position - 1));
        }
    }
        break;
    case 5: {
        if (position == 0) {

            questionTopAnswerHolder.basicInfoText.setText("List of all non-categorical questions");
            questionTopAnswerHolder.basicInfoText.setGravity(Gravity.CENTER | Gravity.BOTTOM);
            questionTopAnswerHolder.headingText.setVisibility(View.INVISIBLE);
        } else {
            populateDynamicUiElements(questionTopAnswerHolder, (position - 1));
        }
    }
        break;
    case 6: {
        if (position == 0) {
            questionTopAnswerHolder.basicInfoText.setText("List of all questions asked by you.");
            questionTopAnswerHolder.basicInfoText.setGravity(Gravity.CENTER | Gravity.BOTTOM);
            questionTopAnswerHolder.headingText.setVisibility(View.INVISIBLE);
        } else {
            populateDynamicUiElements(questionTopAnswerHolder, (position - 1));
        }
    }
        break;
    case 7: {
        if (position == 0) {

            questionTopAnswerHolder.basicInfoText.setText("List of all questions answered by you.");
            questionTopAnswerHolder.basicInfoText.setGravity(Gravity.CENTER | Gravity.BOTTOM);
            questionTopAnswerHolder.headingText.setVisibility(View.INVISIBLE);
        } else {
            populateDynamicUiElements(questionTopAnswerHolder, (position - 1));
        }
    }
        break;
    case 8: {
        if (position == 0) {

            questionTopAnswerHolder.basicInfoText.setText(
                    "All the private questions asked by your faculty students. Visible only to fellow faculty students");
            questionTopAnswerHolder.basicInfoText.setGravity(Gravity.CENTER | Gravity.BOTTOM);
            questionTopAnswerHolder.headingText.setVisibility(View.INVISIBLE);
        } else {
            populateDynamicUiElements(questionTopAnswerHolder, (position - 1));
        }
    }
        break;
    default: {
        populateDynamicUiElements(questionTopAnswerHolder, position);
    }
        break;

    }

}

From source file:org.iota.wallet.ui.fragment.NodeInfoFragment.java

private SpannableString generateCenterSpannableText() {
    SpannableString s = new SpannableString(getString(R.string.transactions));
    s.setSpan(new RelativeSizeSpan(0.75f), 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getActivity(), R.color.colorAccent)), 0,
            s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return s;/*from  w w w . ja  va 2  s  . c o  m*/
}

From source file:io.github.hidroh.materialistic.widget.StoryView.java

public void setPromoted(int change) {
    SpannableString spannable = new SpannableString(String.format(Locale.US, PROMOTED, change));
    spannable.setSpan(new SuperscriptSpan(), 0, spannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new RelativeSizeSpan(0.6f), 0, spannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new ForegroundColorSpan(mPromotedColorResId), 0, spannable.length(),
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    mRankTextView.append(spannable);/*from   w w w. j  a v a  2 s . c om*/
}

From source file:com.ruesga.rview.misc.Formatter.java

@BindingAdapter("userMessage")
public static void toUserMessage(TextView view, String msg) {
    if (msg == null) {
        view.setText(null);//from w ww. ja v a2 s .  c om
        return;
    }

    String message = EmojiHelper.createEmoji(msg);

    // This process mimics the Gerrit formatting process done in class
    // ./gerrit-gwtexpui/src/main/java/com/google/gwtexpui/safehtml/client/SafeHtml.java

    // Split message into paragraphs
    String[] paragraphs = StringHelper.obtainParagraphs(message);
    StringBuilder sb = new StringBuilder();
    boolean formattedMessage = false;
    for (String p : paragraphs) {
        if (StringHelper.isQuote(p)) {
            sb.append(StringHelper.obtainQuote(StringHelper.removeLineBreaks(p)));
            formattedMessage = true;
        } else if (StringHelper.isList(p)) {
            sb.append(p);
            formattedMessage = true;
        } else if (StringHelper.isPreFormat(p)) {
            sb.append(StringHelper.obtainPreFormatMessage(p));
            formattedMessage = true;
        } else {
            sb.append(p);
        }
        sb.append("\n\n");
    }

    String userMessage = StringHelper.removeExtraLines(sb.toString());
    if (!formattedMessage) {
        view.setText(userMessage);
        return;
    }

    if (sQuoteColor == -1) {
        sQuoteColor = ContextCompat.getColor(view.getContext(), R.color.quote);
        sQuoteWidth = (int) view.getContext().getResources().getDimension(R.dimen.quote_width);
        sQuoteMargin = (int) view.getContext().getResources().getDimension(R.dimen.quote_margin);
    }

    String[] lines = userMessage.split("\n");
    SpannableStringBuilder spannable = new SpannableStringBuilder(userMessage
            .replaceAll(StringHelper.NON_PRINTABLE_CHAR, "").replaceAll(StringHelper.NON_PRINTABLE_CHAR2, ""));

    // Pre-Format
    int start = 0;
    int spans = 0;
    while ((start = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start)) != -1) {
        int end = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start + 1);
        if (end == -1) {
            //? This is supposed to be formatted by us. Skip it
            break;
        }

        // Find quote token occurrences
        int offset = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, userMessage, 0, start);
        start -= offset;
        end -= offset;

        // Ensure bounds
        int spanStart = start - spans;
        int spanEnd = Math.min(end - spans - 1, spannable.length());
        if (spanStart < 0 || spanEnd < 0) {
            //Something was wrong. Skip it
            break;
        }
        spannable.setSpan(new RelativeSizeSpan(0.8f), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new TypefaceSpan("monospace"), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        start = end;
        spans++;
    }

    start = 0;
    for (String line : lines) {
        // Quotes
        int maxIndent = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, line);
        for (int i = 0; i < maxIndent; i++) {
            QuotedSpan span = new QuotedSpan(sQuoteColor, sQuoteWidth, sQuoteMargin);
            spannable.setSpan(span, start, Math.min(start + line.length() - maxIndent, spannable.length()),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        // List
        if (StringHelper.isList(line)) {
            spannable.replace(start, start + 1, "\u2022");
            spannable.setSpan(new LeadingMarginSpan.Standard(sQuoteMargin), start,
                    Math.min(start + line.length(), spannable.length()), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        start += line.length() - maxIndent + 1;
    }

    view.setText(spannable);
}