Android EditText + set some words in colour

送分小仙女□ 提交于 2019-11-30 07:53:19

问题


I create EditText boxes dynamically, depending on what is pulled back from the database.

Ie.

            final EditText textV = new EditText(this);
            textV.setText(monEntry);

Is there anyway to set some of the text in the EditText to one colour and another bit to another without using a subString()? Thanks alot if anybody can help!


回答1:


Yes, you can have different colors in different places of the text if you are using SpannableString. Example:

SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");  
final EditText textV = new EditText(this);
// make "Lorem" (characters 0 to 5) red  
textV.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);  
textV.setText(text, BufferType.SPANNABLE);

or you can use html code as below::

textV.setText(Html.fromHtml(html text having 1 in red 2 in green and so on));

There's a more complete example here.

Javadoc for SpannableString




回答2:


public class MainActivity extends Activity implements TextWatcher {

    EditText txt1,txt2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt1=(EditText) findViewById(R.id.editText1);
        txt2=(EditText) findViewById(R.id.editText2);
        txt2.setText(getResources().getString(R.string.str));
        txt1.addTextChangedListener(this);

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
         String string = getResources().getString(R.string.str);
        // String string1=string.toLowerCase();
         try{
                String withHighLightedText = string.replaceAll(s.toString(), "<font color='yellow'>"+s.toString()+"</font>");
                txt2.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
                }catch(Exception ex){

                }

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
}


来源:https://stackoverflow.com/questions/10303166/android-edittext-set-some-words-in-colour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!