Darragh O'Flaherty
Darragh O'Flaherty

Reputation: 1005

Second Click Returns to the original text

Im pretty new to Java and xml and i've run into a problem. I've created an app that displays text and then when a button is hit it changes the text, the problem i have is i would like for the text to return to the original when i hit the button a second time

        final TextView ad1 = (TextView) findViewById(R.id.t5);
          final Button b1 = (Button) findViewById(R.id.b1);

            b1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                  // Perform action on click
                   ad1.setText("random text");

                 }
            });
             }

        <TextView
            android:id="@+id/t5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/t4"
            android:layout_margin="5dp"
            android:gravity="center"
            android:text="@string/t5" 
            android:textColor="#ffffff"/>

         <Button
            android:id="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/t5"
            android:layout_centerHorizontal="true"
            android:layout_margin="10dp"
            android:layout_marginTop="14dp"
            android:text="@string/b1"
            android:textColor="#ffffff" />

Upvotes: 0

Views: 65

Answers (2)

Galax
Galax

Reputation: 365

This does the trick.

String newString = "Whoa!";
String lastString;


public void action_Clicked(View view){
    switch(view.getId()){

    case R.id.button1:
        exchange();
        break;

    }
}

private void exchange(){
    lastString = text.getText().toString();
    text.setText(newString);
    newString = lastString;
}

Upvotes: 0

ToYonos
ToYonos

Reputation: 16833

Try this :

b1.setOnClickListener(new View.OnClickListener()
{
   private String originalText = null;

    public void onClick(View v)
    {
        if (originalText == null) originalText = ad1.getText().toString();

        if (ad1.getText().toString().equals(originalText))
        {
            // Setting a new text
            ad1.setText("random text");
        }
        else
        {
            // Setting back the original text
            ad1.setText(originalText);
        }
    }
});

Upvotes: 1

Related Questions