Y.Jack Y.Jack - 5 months ago 11
Android Question

I want to add a function for my button, but don't know how

That's my XML file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/btFinish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Finish" />
<Button
android:id="@+id/btClicked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Clicked" />
</LinearLayout>


And that's my activity file:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


final Button bt = (Button) findViewById(R.id.btClicked);
bt.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btFinish:
finish();
break;

case R.id.btClicked:
bt.setText("UnClicked");

}
}
});
}
}


I want to add a function that if clicked again, the text reverts to "Clicked".

Answer

Try something like that:

case R.id.btClicked:
    if (bt.getText().equals("UnClicked")
        bt.setText("Clicked");
    else
        bt.setText("UnClicked");
Comments