da_st
da_st

Reputation: 402

Numbers increasing when button clicked

I have this Button:

<Button
       android:id="@+id/button1"
       android:layout_width="130dp"
       android:layout_height="35dp"
       android:layout_alignRight="@+id/editText2"
       android:layout_alignTop="@+id/imageView1"
       android:layout_marginTop="23dp"
       android:text="Increase" />

How can i make it so that whenever the button is clicked, the count in a textview goes up, for example if the number is first 0, and then you click the button it changes to 1?

Upvotes: 0

Views: 183

Answers (3)

Smile
Smile

Reputation: 375

it is very simple ! use this code :

<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Increase" 
   android:onClick="inc"/>

<TextView
   android:id="@+id/text"
   ..../>

and in your activity :

public void inc(View v){
    TextView t = (TextView) findViewById(R.id.text);
    t.setText(String.valueOf(Integer.parseInt(t.getText)+1));
}

Upvotes: 0

Juggernaut93
Juggernaut93

Reputation: 333

You must add a listener to the Button via the Button's setOnClickListener method, passing in an OnClickListener object.

Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int i = Integer.parseInt(myTextView.getText().toString());
        myTextView.setText(String.valueOf(i + 1));
    }
});

where myTextView is the TextView with the counter, obtained with a call to findViewById. Be sure to pass a String to setText, otherwise the method overload with the integer parameter will be called, which has a different meaning (the integer represents a resource id).

Upvotes: 2

Alexis C.
Alexis C.

Reputation: 93862

Attach a listener to the button to handle the click event.

When you click on it, increment a counter variable and update the text of the textview.

Hint: Use String.valueOf(myCounter); to convert the int to a String

Upvotes: 2

Related Questions