0

I'm trying to write a simple code to change the text color when the text is pressed. Can somebody please tell me what is wrong with this code?

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

    TextView text = (TextView) findViewById(R.id.textView2);
    text.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public void OnClick(View v) {
            text.setTextColor(Color.GREEN);
        }

    }
}
Paul
  • 4,160
  • 3
  • 30
  • 56
Kubs
  • 21
  • 1
  • 8
  • Have you tried adding XML property clickable to true? Enabling focusable to true might be a good thing too. – Tiago Dávila Jan 27 '17 at 14:48
  • Yes, I added it but still not working. Thank you for respond – Kubs Jan 27 '17 at 14:51
  • First off all the code regarding touch listener / changing color should be put in the onCreate. `text` should also be made final (only final variables are accessible in anonymous classes). Also it's `onClick` not `OnClick`. Edit: also the onClick method actually tells which which `View` was pressed, so you can just cast `v` to `TextView`. Finally since you only really care about what view was pressed you can just use add an onClickListener, you don't care about what kind of touch event was submitted (up, down etc) – nbokmans Jan 27 '17 at 14:52

4 Answers4

0

You are initializing text outside or before onCreate which is an Exception and you can't set listener outside or before oncreate execution

1.) Declare text as global

2.) Initialize and set listener inside oncreate

public class MainActivity extends AppCompatActivity {

   TextView text ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.textView2);
        text.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
               text.setTextColor(Color.GREEN);    
                return true;
            }
        });
    }
}
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • 1
    There's no need for that. onClick interface already provides you the View that was clicked. Keeping global variables for no reason is not a good thing. – Tiago Dávila Jan 27 '17 at 14:53
  • @TiagoDávila then there suppose to be a function to handle click , which is not here – Pavneet_Singh Jan 27 '17 at 14:54
  • @PavneetSingh a reference to the `TextView` in the scope of `onCreate` is sufficient. – nbokmans Jan 27 '17 at 14:56
  • @nbokmans i know buddy , but to use it somewhere else it needs to be this way , because sooner or later user creates another function to access it – Pavneet_Singh Jan 27 '17 at 14:57
  • Thank you. I get this when running emulator with Pavneet's code:Error:(24, 6) error: reached end of file while parsing Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > Compilation failed; see the compiler error output for details. – Kubs Jan 27 '17 at 15:18
  • @Kubs seems like you missed a brace `}` or something , so make sure curly braces are there with opening and closing match – Pavneet_Singh Jan 27 '17 at 15:25
  • Hello, I ran only "Hello World" text on my phone and it was ok. Then I added Bram's code with OnClickListener and I got this massage back:"Instant Run performed a clean build and install since the installation on the device does not match the local build on disk". I ran it one more time and I got this:"Performing full build and install: On devices with API level below 21, a full build is required if the app is not running". Ps. I have Samsung Galaxy Ace2 with Android 4.1.2 API 16 and got all 'APIs 16' downloaded in Android SDK Manager – Kubs Jan 28 '17 at 10:39
  • @Kubs then you should ask this to Bram why me , accept whatever post you like , close this answer and you can post new question if you like but anyway try run your app first with full build and then hopefully , instant-run works fine , it's just a instant run issue for improvement , don't worry – Pavneet_Singh Jan 28 '17 at 15:24
  • Thank you Pavneet. Sorry for putting my answer here. Since you've answered me, I'd like to ask you one more question: To set more lines in color when pressed do I have to go over the whole code again or e.g. I can add to the line (R.id.textview2) two more id names just after the name 'textview2'? If I shouldn't ask you here, I will post new question. Just please let me know. Thanks in advance – Kubs Jan 28 '17 at 15:57
  • @Kubs you can't ask your all questions here in comments , accept the useful answer , i have already answered your 3 questions as a not accepted answerer – Pavneet_Singh Jan 28 '17 at 16:15
  • Thank you for your reply.I understand now – Kubs Jan 28 '17 at 16:36
0

Adding onTouchListener in Android you need to implement onTouch :

 text.setOnTouchListener(new View.OnTouchListener() {
            @Override public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

You could also change to OnClickListener so your code would be :

public class MainActivity extends AppCompatActivity {
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView text = (TextView) findViewById(R.id.textView2);
        text.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                text.setTextColor(Color.GREEN);
            }
        });
    }
}

OnClickListener - is used for a basic purpose, when we just need a click from a user i.e., click of a button, no drag or gestures on the screen

OnTouchListener - It performs and action on a press/ release on the screen It allows user with combination of move,down-touch,up-touch,finger drag or any movement gesture on the screen

Ahmed Abidi
  • 1,047
  • 12
  • 24
  • Thanks so much Ahmed for explaining difference between onClick and onTouch. Now it's clear. – Kubs Jan 28 '17 at 12:32
0

This should work:

   text.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            text.setTextColor(Color.GREEN);
            return false;
        }
    });

Also this should be in the onCreate like this:

public class MainActivity extends AppCompatActivity {

private TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (TextView) findViewById(R.id.text);
    text.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            text.setTextColor(Color.GREEN);
            return false;
        }
    });
}
}

But I think u mixed up onTouchListener and onClickListener. For only clicks I would recommend using onClickListener. But u were almost there u mixed up both xD.

With onClickListener

public class MainActivity extends AppCompatActivity {
private TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (TextView) findViewById(R.id.text);
    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            text.setTextColor(Color.GREEN);
        }
    });
}
}

EDIT

To toggle the color you can use this:

private TextView text;
private boolean toggle = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (TextView) findViewById(R.id.text);
    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            changeColor(toggle);
        }
    });
}

private void changeColor(boolean toggle){
    if(toggle){
        text.setTextColor(Color.BLACK);
    }else{
        text.setTextColor(Color.GREEN);
    }
    this.toggle = !toggle;
}
Bram Jongebloet
  • 306
  • 1
  • 2
  • 10
  • Hi everyone. It WORKS!:) Huraaaay:) Tried all your codes. Only Bram's 'onCreate' one, strangly didn't want to launch properly..hmmm. Just one more thing - 'what to add to this code to be able to 'unlick' it back from green to black color'? One more time many thanks to all of you!!! :) – Kubs Jan 28 '17 at 12:25
  • Strange that my onCreate didn't work. At me it works fine. Maybe it's because i declared the textView id as '@+id/text'. If it still doesn't work let me know what's wrong. But I added a method how to toggle the textView. U can do it on several ways but i think this one is pretty clear. – Bram Jongebloet Jan 30 '17 at 07:13
0

Nearly you are right

text.setOnTouchListener(new View.OnTouchListener() {        
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // PRESSED
                text.setTextColor(Color.GREEN);
                return true; // if you want to handle the touch event
            case MotionEvent.ACTION_UP:
                // RELEASED
                text.setTextColor(Color.RED);
                return true; // if you want to handle the touch event
        }
        return false;
    }
});

But i suggest you to use animation that is more effective than this Check -http://www.androidhive.info/2013/06/android-working-with-xml-animations/ and https://www.tutorialspoint.com/android/android_animations.htm

Sushant Gosavi
  • 3,647
  • 3
  • 35
  • 55