javaandroidspannablestringspannablespanned

How to display words of different sizes, such as Office or function of Google Docs in Android


I try to do like the Office or Google Docs can enter a different word sizes this feature

Here is my code

input =(EditText)findViewById(R.id.Input_EditText); 
input.addTextChangedListener(new TextWatcher() 
{
    public void onTextChanged(CharSequence s, int start, int before, int count) {   
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {    
    }
    public void afterTextChanged(Editable s) 
    {
        int index = input.getSelectionEnd();
        String nowstr;

        if(index==0)
        {
            //do nothing
        }
        else
        {
            nowstr = s.toString();
            char nowstr_array[] = nowstr.toCharArray();
            show_input = String.valueOf(nowstr_array[index-1]);

            SpannableStringBuilder  spann = new SpannableStringBuilder(show_input);
            AbsoluteSizeSpan word_size = new AbsoluteSizeSpan(40,true);
            spann.setSpan(word_size, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            input.getText().insert(index, spann);
        }
    }
});

But this program will crash...

then,I try to do

Toast.makeText(MainActivity.this, spann, Toast.LENGTH_SHORT).show();
//input.getText().insert(index, spann);

But doing so can be displayed...

That is why?


Solution

  • public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                beforeText = s.toString() ;
            }
    
            public void afterTextChanged(Editable s) {
                int index = input.getSelectionEnd();
                String nowstr;
    
                if (index == 0) {
                    // do nothing
                } else {
                    if (beforeText.length() < s.toString().length()) {
                        nowstr = s.toString();
                        char nowstr_array[] = nowstr.toCharArray();
                        String show_input = String.valueOf(nowstr_array[index - 1]);
    
                        SpannableStringBuilder spann = new SpannableStringBuilder(
                                show_input);
                        AbsoluteSizeSpan word_size = new AbsoluteSizeSpan(40, true);
                        spann.setSpan(word_size, 0, 1,
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        input.removeTextChangedListener(this) ;
                        input.getText().replace(index-1, index, spann) ;
                        input.addTextChangedListener(this) ;
    
                    }
                }
            }
    
        });
    

    beforeText is a global variable