android TextView : Change Text Color on click

后端 未结 2 1741
灰色年华
灰色年华 2020-12-03 07:23

I have a textfield that behaves like a local link, clicking on it fetches an image from database and shows it. It doesn\'t ping to server all the time.

Here is the x

相关标签:
2条回答
  • 2020-12-03 07:56

    You can create your own TextView class that extends the Android TextView class and override the onTouchEvent(MotionEvent event)

    You can then modify the instances text color based on the MotionEvent passed.

    For example:

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
           // Change color
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
           // Change it back
        }
        return super.onTouchEvent(event);
    }
    
    0 讨论(0)
  • 2020-12-03 08:01

    I like what Cristian suggests, but extending TextView seems like overkill. In addition, his solution doesn't handle the MotionEvent.ACTION_CANCEL event, making it likely that your text will stay selected even after the clicking is done.

    To achieve this effect, I implemented my own onTouchListener in a separate file:

    public class CustomTouchListener implements View.OnTouchListener {     
        public boolean onTouch(View view, MotionEvent motionEvent) {
        switch(motionEvent.getAction()){            
                case MotionEvent.ACTION_DOWN:
                ((TextView)view).setTextColor(0xFFFFFFFF); //white
                    break;          
                case MotionEvent.ACTION_CANCEL:             
                case MotionEvent.ACTION_UP:
                ((TextView)view).setTextColor(0xFF000000); //black
                    break;
        } 
            return false;   
        } 
    }
    

    Then you can assign this to whatever TextView you wish:

    newTextView.setOnTouchListener(new CustomTouchListener());

    0 讨论(0)
提交回复
热议问题