如果 edittext 包含该单词,如何为 Android 文本的一部分着色

2023-12-27

只要用户在编辑文本中输入“house”,我就会尝试为单词(house)着色。这就是我所做的:

if (textA.getText().toString().equals("house")){
    String name = String.valueOf(textA.getText().toString().equals("house"));
    name.setTextColor(Color.parseColor("#bdbdbd"));
}

我的xml如下

<LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="15dp"
                    android:layout_marginEnd="15dp"
                    android:orientation="vertical"
                    android:padding="5dp">


                    <EditText
                        android:id="@+id/textA"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:inputType="textMultiLine"
                        android:maxLines ="4"
                        android:maxLength ="2000"
                        android:textColorHint="@color/grey"
                        android:background="@android:color/transparent"
                        android:gravity="top"/>

                </LinearLayout>

但这会导致应用程序崩溃。不知道我做错了什么。我是安卓新手。请问有什么建议吗?


this works for me

 textA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str="home";
            Spannable spannable =textA.getText();
            if(s.length() != 0) {
                textA.setTextColor(Color.parseColor("#0000FF"));
                ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);
                String s1 = s.toString();
                int in=0; // start searching from 0 index

// keeps on searching unless there is no more function string found
                while ((in = s1.indexOf(str,in)) >= 0) {
                    spannable.setSpan(
                            fcs,
                            in,
                            in + str.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    // update the index for next search with length
                    in += str.length();
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果 edittext 包含该单词,如何为 Android 文本的一部分着色 的相关文章

随机推荐