Click the button and open another Activity

Asked

Viewed 38,768 times

9

I am developing an application in JAVA , and will have 2 options for the person to choose, I want when she press in 1 of the 2 buttons open a new Activity in the application, Can anyone please tell me what the code for this ? I’m using Android Studio.

1 answer

13


For this you can use the startActivity method ( Documentation )

This method requests as a parameter a Intent

This should be informed a Context (in your Activity case) and class of the Activity you wish to open:

Intent intent = new Intent(this, SegundaActivity.class);
startActivity(intent);

ADD CLICK ON A BUTTON THROUGH XML:

In His xml in the first element add the following line:

xmlns:tools="http://schemas.android.com/tools"

With this you can add what is the context class of this xml:

 tools:context="seu.pacote.app.SuaActivity"

After, we will inform on the button which method it will call:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
<!-- ira chamar o metodo proximaTela -->
    android:onClick="proximaTela"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="-2dp" />

In Java add a public method void and that you receive a View as a parameter:

public class SuaTela extends AppCompatActivity {

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

    public void proximaTela(View view){

        Intent intent = new Intent(this, SegundaActivity.class);
        startActivity(intent);
    }
}
  • Thank you very much.

  • Just remember that you can’t forget to declare the new Activity on Androidmanifest.xml <Activity android:name=". Suanovaactivity" />

  • Thank you very much Thiago!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.