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.
11 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