0

I have an editText in which i want to bold the text that i select. I'm using the Contextual Action Bar with a button to bold a selected word. The problem is that if I bold a word I can't bold the other onesm and if i remove the span from that word, I can't add it again. et is the editText in which i write, and i use also 2 SpannableString to catch the remaining text keeping eventual spans added before on it.

CUSTOM CALLBACK

cs1 = new StyleSpan(Typeface.BOLD);

class CustomCallback implements ActionMode.Callback {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {

    //exploiting the CAB

    MenuInflater inflater = mode.getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
    menu.removeItem(android.R.id.selectAll);
    return true;
}

public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    return false;
}

ACTION ADD BOLD

public boolean onActionItemClicked(ActionMode mode, MenuItem item) {


    int start = et.getSelectionStart();
    int end = et.getSelectionEnd();




    SpannableStringBuilder s_before,s_next;

    SpannableStringBuilder ssb = new SpannableStringBuilder(et.getText().subSequence(start, end));
    s_before= new SpannableStringBuilder (et.getText().subSequence(0, start));
    s_next= new SpannableStringBuilder (et.getText().subSequence(end, et.length()));



    switch(item.getItemId()) {


    case R.id.bold:

        int a=ssb.getSpanStart(cs1);
        int b=ssb.getSpanEnd(cs1);


        if(a==-1 && b==-1){

            ssb.setSpan(cs1, 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        else{
            ssb.removeSpan(cs1);
        }
        et.setText("");
        et.append(s_before);
        et.append(ssb);
        et.append(s_next);

        return true;

How can i solve it? Thanks in advance.

e_ori
  • 845
  • 1
  • 11
  • 29

1 Answers1

3

I've just put a RichEditText library https://github.com/kemallette/RichEditText which adds bold/italic/strike/underline.. and a few other font styles functionalities. It also adds a bunch of great validations.

If that doesn't fit your needs, you'll need to focus on keeping track of where your spans are, what type they are and that they're being adjusted/re-added. Take a look at the RichEditText and RichTextWatcher classes in the above library. It'll give you a better idea of what's actually happening when text changes in your EditText.

KMDev
  • 615
  • 6
  • 10