7

I want to implement a function,

EditText user when entering text, you can make changes in accordance with the set font size,

Such as Google Docs of Office,

enter image description here

Now I found a way to SpannableString, but read some examples seem unable to reach my needs

int index = input.getSelectionEnd();
SpannableString  spann = new SpannableString(show_input);
AbsoluteSizeSpan word_size = new AbsoluteSizeSpan(18,true);
spann.setSpan(word_size, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
input.getText().insert(index, spann);

So is there any way to provide it?

Ban Lin
  • 95
  • 2
  • 10

2 Answers2

7

Looks like you want to change size of selected text:

int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
Spannable text=(Spannable)editText.getText();
text.setSpan(new AbsoluteSizeSpan(NEW_TEXT_SIZE, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(text);

Use AbsoluteSizeSpan to change for actual size or RelativeSizeSpan for proportional size.

lewkka
  • 1,019
  • 15
  • 25
0

I trird to add TextWatcher(),

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?

Ban Lin
  • 95
  • 2
  • 10