Button click start new activity android

A classic Android question!

To start a new activity when a button is clicked in Android, you can follow these steps:

Step 1: Create a new activity

In your Android project, create a new Java class that extends the Activity class. For example, let's call it NewActivity.java.

Step 2: Define the button in your layout

In your main activity's layout file (e.g., activity_main.xml), add a button with an ID, for example:

<Button
    android:id="@+id/start_new_activity_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start New Activity" />

Step 3: Set the button's click listener

In your main activity's Java code, find the button and set its click listener using the setOnClickListener() method. When the button is clicked, the onClick() method will be called.

For example:

public class MainActivity extends AppCompatActivity {
    private Button startNewActivityButton;

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

        startNewActivityButton = findViewById(R.id.start_new_activity_button);
        startNewActivityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Start the new activity here
            }
        });
    }
}

Step 4: Start the new activity

In the onClick() method, use the Intent class to create a new intent that starts the new activity. You can pass data to the new activity using the putExtra() method.

For example:

startNewActivityButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, NewActivity.class);
        intent.putExtra("key", "value");
        startActivity(intent);
    }
});

Step 5: Declare the new activity in your AndroidManifest.xml file

Make sure to declare the new activity in your AndroidManifest.xml file:

<activity
    android:name=".NewActivity"
    android:exported="true" />

That's it! When you run your app and click the button, the new activity should start.

Remember to replace NewActivity with the actual name of your new activity class.