Android Studio: How to change a button's text onClick

I am very new to Android. I am trying to make a simple tic tac toe game. I have 9 buttons set up evenly across the screen with gray lines between. I just need the buttons to say either 'X' or '0' when pressed. How do you change the buttons text when you click it? I should be able to figure out the logic on whether it should be an X or an O once I can actually figure out how to change the button text.

1

1 Answer

You can try something like this: (You need to fill in your button id.)

public class MainActivity extends Activity implements View.OnClickListener { private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.yourbuttonid); btn.setOnClickListener(this); } @Override public void onClick(View v) { btn.setText("X"); } } 

If you want to do this with multiple buttons you need to check which button is clicked, like this:

@Override public void onClick(View v) { if(v.getId() == R.id.yourbuttonid) { btn.setText("X"); }else if(v.getId() == R.id.yourbuttonid2){ btn2.setText("X"); } } 

Hope that solves your problem. If you have any questions, feel free to ask ;)

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like