How to start new activity on button click

后端 未结 24 1707
傲寒
傲寒 2020-11-21 05:54

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?

24条回答
  •  星月不相逢
    2020-11-21 06:38

    From the sending Activity try the following code

       //EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
        public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           ....
    
            //Here we declare our send button
            Button sendButton = (Button) findViewById(R.id.send_button);
            sendButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //declare our intent object which takes two parameters, the context and the new activity name
    
                    // the name of the receiving activity is declared in the Intent Constructor
                    Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
    
                    String sendMessage = "hello world"
                    //put the text inside the intent and send it to another Activity
                    intent.putExtra(EXTRA_MESSAGE, sendMessage);
                    //start the activity
                    startActivity(intent);
    
                }
    

    From the receiving Activity try the following code:

       protected void onCreate(Bundle savedInstanceState) {
     //use the getIntent()method to receive the data from another activity
     Intent intent = getIntent();
    
    //extract the string, with the getStringExtra method
    String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
    

    Then just add the following code to the AndroidManifest.xml file

      android:name="packagename.NameOfTheReceivingActivity"
      android:label="Title of the Activity"
      android:parentActivityName="packagename.NameOfSendingActivity"
    

提交回复
热议问题