In my program, when the user presses a button, I want to set the text to something else based on what is already there, but it is not working.
When I click on the buttons, nothing happens, the text stays the same
This is the xml layout where the buttons are made. they call the function nextVal
<Button
android:id="@+idk/kbutton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="nextVal"
android:text="@string/zero" />
<Button
android:id="@+idk/kbutton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="nextVal"
android:text="@string/x" />
<Button
android:id="@+idk/kbutton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="nextVal"
android:text="@string/one" />
The function that is called
public void nextVal(View view)
{
Button b = (Button) findViewById(view.getId());
System.out.println(b.getText().toString());
switch(view.getId())
{
case R.idk.kbutton4:
if(b.getText().toString() == "0")
b.setText("1");
else if(b.getText().toString() == "1")
b.setText("x");
else if(b.getText().toString() == "x")
b.setText("0");
break;
case R.idk.kbutton3:
if(b.getText().toString() == "0")
b.setText("1");
if(b.getText().toString() == "1")
b.setText("x");
if(b.getText().toString() == "x")
b.setText("0");
break;
case R.idk.kbutton2:
if(b.getText().toString() == "0")
b.setText("1");
if(b.getText().toString() == "1")
b.setText("x");
if(b.getText().toString() == "x")
b.setText("0");
break;
}
}
You are using the == operator to compare two strings. The == operator checks whether the reference is the same, not whether the contents are equivalent.
Instead, you should use b.getText.ToString().equals(“x”);
That being said, I have some additional suggestions. You’re using findViewById() to find a view that you’re already being passed. You can replace the findViewById(view.getId()) and just cast the View to Button instead.
Also, you can get rid of the switch statement, because it’s really doing you no good except to clutter up the code. You are doing the exact same thing no matter the case, so why bother? Just replace it with the contents of one of the possibilities.
So your nextVal() might look like: