Click the button in Android to start another Activity and transfer values between activities

Posted by 2DaysAway on Fri, 10 Jan 2020 15:24:36 +0100

scene

Click the button in the first Activity to start the second Activity, close the second Activity and return to the first Activity.

Pass the value to the second Activity in the first Activity, and get and display it in the second Activity.

Open the second Activity

Activity value passing

 

 

Note:

Blog:
https://blog.csdn.net/badao_liumang_qizhi
Pay attention to the public address
Domineering procedural ape
Get programming related ebooks, tutorials and free downloads.

Realization

Start another Activity

In the click event of the button in the first Activity

  Button secondActivityButton  =  (Button)findViewById(R.id.secondActivity);
        secondActivityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //The first parameter is the current Activity The second parameter is to start Activity
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });

Then in the click event of the close button in the second Activity

         Button closeButton = (Button) findViewById(R.id.closeButton);
         closeButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 finish();
             }
         });

Start Activity and pass value

In the button click event of the first Activity

     Button paramActivityButton  =  (Button)findViewById(R.id.paramActivity);
        paramActivityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                //Data in the form of multiple key value pairs can be passed
                intent.putExtra("key","Domineering and rogue temperament");
                intent.putExtra("key1","Domineering procedural ape");
                startActivity(intent);
            }
        });

In the click event of the button in the second Activity

        Button valueButton = (Button) findViewById(R.id.valueButton);
        valueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String valueString = (String)getIntent().getExtras().get("key");
                String valueString1 = (String)getIntent().getExtras().get("key1");
                Toast.makeText(SecondActivity.this,"The first parameter obtained is:"+valueString+"The second parameter is:"+valueString1,Toast.LENGTH_LONG).show();
            }
        });

Topics: Android Programming