lord_sneed
lord_sneed

Reputation: 824

Android: On Button Click, Maintain or Change Value in the Same Activity

I have a randomly generated integer displayed on the screen and when the user clicks a button, I want that number to update with a new number or stay the same (depending on which button), but staying on the same activity.

How is the value refreshed/updated while staying on the same activity?

public class ClassName extends Activity implements OnClickListener  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name);
        int currentNum = randNum();
        TextView myTextView = (TextView) findViewById(R.id.current_number); 
        myTextView.setText("Current Number: " + String.valueOf(currentNum));
        okButton = (Button) findViewById(R.id.num_confirmation);
        okButton.setOnClickListener(this);
        changeButton = (Button) findViewById(R.id.change_num);
        changeButton.setOnClickListener(this);
        // set 'currentNumber' accordingly
        // reprint value
    }

    @Override
    public void onClick(View v) {

    }

One of the things I want to do is maintain the same value when a button is clicked (i.e. currentNum stays the same). The other thing is to change the value (with a different button click) with a method I have that returns a new number (i.e. currentNumber = methodCall();).

How is this done?

Upvotes: 0

Views: 2081

Answers (2)

adarsh
adarsh

Reputation: 6978

You could either use the switch case to find the id and add the code there. Or in the layout xml file for the activity, in the button you want to write a onClick method

For button 1

android:onClick="newNum"

For button 2

android:onClick="doNothing"

Then, add these methods, to your activity class

public void newNum(View v) {
    myTextView.setText("Current Number: " + String.valueOf(currentNum+5));
}

public void doNothing(View v) {
    // Do nothing here
}

Upvotes: 0

Mohsin Naeem
Mohsin Naeem

Reputation: 12642

just do this

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.num_confirmation:
        //do nothing in your current scenario 
        break;
    case R.id.change_num:
        myTextView.setText("Current Number: " + String.valueOf(currentNum+5)); 
        break;


    default:
        break;
    }

Upvotes: 1

Related Questions