Search code examples
androidonclickonclicklistener

Android Studio OnClick just working once


when I try to push the button it only works once...

public class MainActivity extends AppCompatActivity {
TextView txt;
Button btn;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt = (TextView) findViewById(R.id.mytext);
    btn = (Button) findViewById(R.id.button1);

    btn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){

            txt.setText("" +1);

        }
    } );

how can I solve it? Thanks a lot


Solution

  • I guess what you trying to do is this:

    public class MainActivity extends AppCompatActivity {
    TextView txt;
    Button btn;
    private int mCounter = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView) findViewById(R.id.mytext);
        btn = (Button) findViewById(R.id.button1);
    
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
    
                txt.setText("" + mcounter++);
    
            }
        } );
    

    Now when you click on the button the text will be 0 on the first time and then counting up every time you click the button. The problem with your code is, that it is no arithmetic operation, so the onclickmethod is called every time, but you have the same text every time too