1. 程式人生 > >多個Activity中傳遞簡單引數

多個Activity中傳遞簡單引數

佈局檔案:

actiity_main:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnStartAty"
        android:text="啟動另一個Activity"/>

</RelativeLayout>

activity_the_aty:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TheAty">

    <TextView
        android:id="@+id/theAty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

TheAty:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class TheAty extends AppCompatActivity {

    private TextView tv;

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

        Intent i = getIntent();
        Bundle data = i.getExtras();

        tv = (TextView) findViewById(R.id.theAty);
//        tv.setText(i.getStringExtra("data"));
        tv.setText(data.getString("name"));
    }
}

MainActivity:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.btnStartAty).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, TheAty.class);
//                i.putExtra("data", "Hello World");

                Bundle b = new Bundle();
                b.putString("name", "Bundle");
                i.putExtras(b);

                startActivity(i);
            }
        });
    }
}