1. 程式人生 > >Android 介面之間傳值筆記

Android 介面之間傳值筆記

Android開發中,用到的介面之間資料傳值方法:

       Intent intent = new Intent(this,SecondActivity.class);

        //方法一:
        String title = "我是來自第一個介面";

        intent.putExtra("string_name",title);

        //方法二
        SecondBean bean = new SecondBean();
        bean.setAge(18);
        bean.setName("FlyToSky");

        Bundle bundle = new Bundle();
        bundle.putSerializable("bean",bean);
        intent.putExtra("bundle",bundle);

        startActivity(intent);

獲取值:

        Intent intent = getIntent();

        //方法一
        String title = intent.getStringExtra("string_name");

        //方法二
        SecondBean bean = (SecondBean) intent.getBundleExtra("bundle").getSerializable("bean");

注意:對於傳值的實體類,需要實現 Serializable,程式碼如下:

public class SecondBean implements Serializable {
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}