Activity and Intent

 Activity and Intent


An activity is a single, focused thing that the user can do. Activities in Android are used to present user interfaces and to interact with the user. An intent is a messaging object used to request an action from another component of the application.


Here's an example of how to create an activity and pass data between activities using intents:


java


public class MainActivity extends AppCompatActivity {

   

   private Button button;

   

   @Override

   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

       

       button = findViewById(R.id.button);

       button.setOnClickListener(new View.OnClickListener() {

           @Override

           public void onClick(View v) {

               Intent intent = new Intent(MainActivity.this, SecondActivity.class);

               intent.putExtra("key", "Hello from MainActivity");

               startActivity(intent);

           }

       });

   }

}

scss


public class SecondActivity extends AppCompatActivity {

   

   private TextView textView;

   

   @Override

   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_second);

       

       textView = findViewById(R.id.textView);

       Bundle bundle = getIntent().getExtras();

       if (bundle != null) {

           String message = bundle.getString("key");

           textView.setText(message);

       }

   }

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...