Domanda

I'm using TextWatcher to change the color of the text of the EditText. I have 2 RadioButtons, I wish the color would change when selecting a radio button. For example, if I click on radio1 the text should turn red, however if I click the radio2 the color should be green. How do I call the Listner to radioButton? This is my TextWatcher:

TextWatcher watcher= new TextWatcher() {
            public void afterTextChanged(Editable s) { 
                if (mRadioGroup.getCheckedRadioButtonId() == R.id.radio1) {
                    mIm.setTextColor(Color.parseColor("#228b22"));
                }
                else {
                    mIm.setTextColor(Color.parseColor("#FF0000"));
                }

            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                    }
                };
        mIm.addTextChangedListener(watcher);
È stato utile?

Soluzione

I'm not sure why you are even using a TextWatcher here. What you need is onCheckedChangeListener and change the text color in onCheckedChange() as you are now.

mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChange(RadioGroup group, int id)
    {
         switch (id)
         {
             case (R.id.radio1):
               mIm.setTextColor(Color.parseColor("#228b22"));
               break;
             default:
             mIm.setTextColor(Color.parseColor("#FF0000"));
         }
   }
});

Altri suggerimenti

TextWatcher is for watching text fields. You need to handle the onClick for the button. Something like this:

  @Override
  public void onClick (View v) 
  {
    switch (v.getId())
    {
      case R.id.red_text:
        mIm.setTextColor (Color....);
        break;
      case R.id.green_text:
        mIm.setTextColor (Color....);
        break;
    }
  }

Don't forget to set the OnClickHandler for the radio buttons.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top