Page Redirect using Intent-AGN HUB

Steps:

  1. Create Two Activities:

    • Let's assume we have MainActivity (source activity) and SecondActivity (destination activity).

  2. Define Activities in AndroidManifest.xml: Ensure both activities are registered in the manifest.

  3. <activity android:name=".MainActivity" />

  4. <activity android:name=".SecondActivity" />

  5. Set Up the Button in the Layout: In activity_main.xml (layout file for MainActivity), add a button.

  6. <Button

  7.     android:id="@+id/buttonRedirect"

  8.     android:layout_width="wrap_content"

  9.     android:layout_height="wrap_content"

  10.     android:text="Go to Second Page"

  11.     android:layout_gravity="center" />

  12. Implement the Intent in MainActivity: Use an Intent to navigate to SecondActivity.

  13. import android.content.Intent

  14. import android.os.Bundle

  15. import android.widget.Button

  16. import androidx.appcompat.app.AppCompatActivity


  17. class MainActivity : AppCompatActivity() {

  18.     override fun onCreate(savedInstanceState: Bundle?) {

  19.         super.onCreate(savedInstanceState)

  20.         setContentView(R.layout.activity_main)


  21.         // Find the button

  22.         val buttonRedirect: Button = findViewById(R.id.buttonRedirect)


  23.         // Set a click listener to redirect to SecondActivity

  24.         buttonRedirect.setOnClickListener {

  25.             val intent = Intent(this, SecondActivity::class.java)

  26.             startActivity(intent)

  27.         }

  28.     }

  29. }

  30. Create the Destination Activity: Create a new activity called SecondActivity.

  31. import android.os.Bundle

  32. import androidx.appcompat.app.AppCompatActivity


  33. class SecondActivity : AppCompatActivity() {

  34.     override fun onCreate(savedInstanceState: Bundle?) {

  35.         super.onCreate(savedInstanceState)

  36.         setContentView(R.layout.activity_second)

  37.     }

  38. }

  39. Set Layout for SecondActivity: Create a layout file activity_second.xml.

  40. <TextView

  41.     android:layout_width="wrap_content"

  42.     android:layout_height="wrap_content"

  43.     android:text="Welcome to Second Page!"

  44.     android:layout_gravity="center"

  45.     android:textSize="18sp" />


Explanation:

  1. Intent: Used to start a new activity. It requires:

    • Current context (this).

    • The class of the destination activity (SecondActivity::class.java).

  2. startActivity(intent): Starts the new activity.


Result:

When you click the button in MainActivity, it will navigate to SecondActivity, displaying the message "Welcome to Second Page!".


Comments

Popular posts from this blog

RadioButtons-AGN HUB

Checkbox- AGN HUB

Timepicker- AGN HUB