activity传递数据

147 阅读1分钟

传递基本类型

使用Intent类中的putExtra方法,可以利用这个方法传递基本的数据类型

Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
intent.putExtra("name","你的名字");
intent.putExtra("age",20);
startActivity(intent);

接受参数

使用getIntent()方法,将参数获取出来,get 后面是你传递类型,不知道走的putExtra是那个重载方法的,可以ctrl + 鼠标右击就可以看到你是用的那个重载方法了

        Intent intent = getIntent();
        intent.getStringExtra("name");
        intent.getIntExtra("age", 0);

传递复杂类型

当基本类型不能够满足我们的需求的时候,或者是想传递一个对象的时候我们可以使用Bundle类用来传递

                Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
                Bundle bundle = new Bundle();
                ArrayList<Card> card = new ArrayList<>();
                Card  item =  new Card();
                item.name="你的名字";
                item.age=20;
                card.add(item);
                bundle.putSerializable("people",card);
                intent.putExtra("bundle",bundle);
                startActivity(intent);

上面的例子中传递的是一个ArrayList类型,使用Bundle类中的putSerializable方法,这个方法接受一个String类型作为key,一个Serializable的类型作为value,需要注意的是,ArrayList 泛型的实体类,一定要实现Serializable

Card.java

import java.io.Serializable;

public class Card implements Serializable {
    public String name;
    public int age;
	
    // 重载方法,可以直接toString 直接将数据打印出来
    @Override
    public String toString() {
        return "Card{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

接受获取数据

首先使用intent.getBundleExtra获取到传递的Bundle对象,然后在从Bundle对象中使用bundle.getSerializable获取具体传递的数值

        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("bundle");
        Log.d(TAG, "getInit: " + bundle.getSerializable("people").toString());