【问题标题】:How to change typeface programmatically in edittext properly?如何在edittext中以编程方式正确更改字体?
【发布时间】:2019-12-31 06:47:16
【问题描述】:

我正在尝试创建一个基本的文本编辑器。我几乎实现了我想做的事情,但存在一些问题。当我按下“B”按钮时,它会使文本变为粗体。如果我继续写而不给空间并再次按“B”按钮,我写的所有字母都会正常。但我想保持已经粗体的字母粗体。当我给空间时,它会按我的意愿工作,变为粗体、斜体或正常。以下是我的部分代码:

 editor.textChangedListener {
        beforeTextChanged { _, _, _, _ ->
            val length = editor.text?.length
            length?.let {
                if (it > 0) {
                    val styleSpan = when {
                        isBold && isItalic -> StyleSpan(Typeface.BOLD_ITALIC)
                        isBold && !isItalic -> StyleSpan(Typeface.BOLD)
                        !isBold && isItalic -> StyleSpan(Typeface.ITALIC)
                        else -> StyleSpan(Typeface.NORMAL)
                    }
                    val spannable = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    if (it < start) start = 0
                    editor.text?.setSpan(styleSpan, start, it, spannable)
                }
            }
        }
    }
    boldButton.onClick {
        isBold = !isBold
        val image = when (isBold) {
            true -> R.drawable.ic_bold_active
            false -> R.drawable.ic_bold
        }
        start = editor.text!!.length
        boldButton.setImageResource(image)
    }

【问题讨论】:

  • 问题出在哪里??我在这里没有看到任何明确的问题。
  • 我刚刚尝试了这个解决方案。我的问题是我不想更改所有文本的字体。当我单击粗体时,它会使所有字符串变为粗体。这就是为什么我将 setSpan 与索引一起使用。但它也不起作用。

标签: android kotlin android-edittext editor


【解决方案1】:

要改变字体,你可以使用类似这样的东西。

TextView tv = (TextView) findViewById(R.id.tvname);
Typeface face = Typeface.createFromAsset(getAssets(),
        "fonts/epimodem.ttf");
tv.setTypeface(face);

你也可以试试html

textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));

【讨论】:

    【解决方案2】:

    当点击粗体或斜体按钮时,您可以在更改字体时更新。

    将以下方法添加到您的代码中

     fun onUpdateTypeface() {
    
        when {
            isBold && isItalic ->
                view?.tvForgetPassword?.setTypeface(null, Typeface.BOLD_ITALIC);
            isBold && !isItalic ->
                view?.tvForgetPassword?.setTypeface(null, Typeface.BOLD);
            !isBold && isItalic ->
                view?.tvForgetPassword?.setTypeface(null, Typeface.ITALIC);
            else -> view?.tvForgetPassword?.setTypeface(null, Typeface.NORMAL);
        }
    }
    

    更新你的 onClick 方法

    boldButton.onClick {
        isBold = !isBold
        val image = when (isBold) {
            true -> R.drawable.ic_bold_active
            false -> R.drawable.ic_bold
        }
        start = editor.text!!.length
        boldButton.setImageResource(image)
        onUpdateTypeface()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      相关资源
      最近更新 更多