Android_Slip_1A

Step1:

Open Android Studio and create a new project with an Empty Activity template.

In the res/layout/activity_main.xml file, add a Button widget:

    <Button
    android:id="@+id/buttonSendMessage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send Message"
    android:onClick="sendMessage"/>


In the MainActivity.java file, implement the sendMessage method:
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

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

    public void sendMessage(View view) {
    Intent intent = new Intent(this, SecondActivity.class);
    intent.putExtra("message", "Hello");
    startActivity(intent);
    }
    }


Step2:

Create a new activity by right-clicking on the app folder in the Project Explorer, then selecting New -> Activity -> Empty Activity. Name it SecondActivity.

In the SecondActivity.java file, retrieve the message from the Intent and display it:

    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;
    public class SecondActivity extends AppCompatActivity {

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

    Intent intent = getIntent();
    String message = intent.getStringExtra("message");

    TextView textView = findViewById(R.id.textViewMessage);
    textView.setText(message);
    }
    }


In the res/layout/activity_second.xml file, add a TextView to display the message:

    <TextView
    android:id="@+id/textViewMessage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Message will appear here"/>


No comments:

Post a Comment