java - 如何在Android中显示不同大小的文字,例如Office或Google Docs的功能

标签 java android spannablestring spannable spanned

我尝试做像Office或Google Docs可以输入不同字号这个功能

这是我的代码

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);
        }
    }
});

但是这个程序会崩溃...

然后,我尝试这样做

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

但是这样做可以显示...

这就是为什么?

最佳答案

因为在 aftertextchanged 方法中,您获取文本并更改文本大小,最后将文本插入到 edittext 中,但是该方法将导致 textWatcher 监听器在 aftertextchanged 后运行,并且在该方法中您还更改了文本,因此这是一个死循环,但是如果你使用toast,它不会插入文本,那么就不会引起监听器,然后它就可以工作了:)

关于java - 如何在Android中显示不同大小的文字,例如Office或Google Docs的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33469902/

相关文章:

java - 将两个字节读入一个整数?

java - 嵌套异常是 java.lang.IllegalStateException : Cannot convert value of type [java. lang.String] 到所需类型

java - 您如何找到 Java 中 sleep 中断的根本原因?

android - Android 图案锁定屏幕上的时钟字体

java - 为什么 AsyncTask 不适合长时间运行的操作

android - StyleSpan 未应用于 TextView 中的 SpannableString

Android,setSpan 两次?

android - 我怎样才能让 EditText 具有可点击的 Spannables 并且仍然可以通过 longClick 选择?

java - 为什么我的程序无法运行?

android - AAPT2资源失败错误