-1

I am just starting learning android and i started making an experimental app.My goal is when i press the button ,the text should change in this way:when it is "OFF" ,pressing the button should make it "ON" and the opposite. Here is my code:

public class MainActivity extends AppCompatActivity {

    private TextView textView;

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

        textView = (TextView) findViewById(R.id.TextView);
        Button button = (Button) findViewById(R.id.button);

        button.setOnTouchListener(new View.OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                String text="";
                    if (textView.getText().equals("ON")) {
                       text="OFF";
                    } else if (textView.getText().equals("OFF")) {
                        text="ON";
                    }
                textView.setText(text);
                return false;
            }

        });
    }
}

When i run it and press the button ,the app shows the "OFF" for a fraction of a second and then "ON" again.This happens every time i press the button."ON" is the default value.I just would like to know what am i missing here?

pfaehlfd
  • 130
  • 1
  • 12

2 Answers2

3

You have to use setOnClickListener, not setOnTouchListener because touch is very more sensible to the touch than the click. Write this code:

button.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        String text="";
            if (textView.getText().equals("ON")) {
               text="OFF";

            }
            else if (textView.getText().equals("OFF")) {
                text="ON";

            }
        textView.setText(text);
    }

});
Curio
  • 1,331
  • 2
  • 14
  • 34
1

There are tons of MotionEvent s that get generated on touch. Look for Action Put your code inside event.getAction()==MotionEvent.ACTION_DOWN

Zakir
  • 2,222
  • 21
  • 31