RennerStudios
RennerStudios

Reputation: 64

Why wont my Android button respond when it is clicked?

Sorry for the simple question (im new to android development)

Ive created a button on a layout with the ID of backToMain.

When the button is pressed, I want the button to return to the activity_main layout.

I have wrote the following code:

public class Instructions extends Activity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.instructions);

        Button returnHome = (Button) findViewById(R.id.backToMain);
        returnHome.setHapticFeedbackEnabled(true);
        returnHome.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
                setContentView(R.layout.activity_main);
            }
        });
    }
}

When I compile and run the game, the button does not do anything. Can anyone help? Thanks!

Here is the XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

   <Button
       android:id="@+id/backToMain"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:text="@string/home" 
   />

</LinearLayout>

</ScrollView>

Upvotes: 0

Views: 109

Answers (2)

John P.
John P.

Reputation: 4388

If the following code does not work you should post the layout where the Button is so we can see what is going on with your XML.

returnHome.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {

        Log.d("TAG", "-----------Button click-------------");

        Toast.makeText(Instructions.this, "Button click", Toast.LENGTH_LONG).show();

        Instructions.this.finish();

    }

});

Upvotes: 0

karvoynistas
karvoynistas

Reputation: 1285

Your listener method should look like this :

returnHome.setOnClickListener(new OnClickListener() 
    {
        public void onClick(View v) 
        {
              Intent intent = new Intent(getApplicationContext(),MainActivity.class);
              startActivity(intent);
        }
    });

It works!

Upvotes: 1

Related Questions