天天看點

Activity之間的資料傳輸

1.通信方式:

Activity之間的資料傳輸

2.通過intent傳遞:

//傳資料
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("name", "ysl");
                intent.putExtra("age", 22);
                startActivity(intent);

//取資料
String name = getIntent().getStringExtra("name");
        int age = getIntent().getIntExtra("age", 0);
           

3.通過bundle傳輸:

//傳資料
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("name1", "Mjj");
                bundle.putInt("age1", 18);
                intent.putExtras(bundle);

                startActivity(intent);

//取資料
String name1 = getIntent().getStringExtra("name1");
        int age1 = getIntent().getIntExtra("age1", 0);
           

4.差別:

其實intent的傳遞底層用的還是bundle的傳遞方法。

看intent的源碼:

Activity之間的資料傳輸
Activity之間的資料傳輸

Bundle可以傳輸的類型有哪些:

Activity之間的資料傳輸

包括的類型特别多。可以根據自己的需求使用。