欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler传递对象

程序员文章站 2022-07-14 16:43:28
...
PersonBean

public class PersonBean {
    String name;
    int age;

    public PersonBean(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

public class MainActivity extends Activity {

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 111) {
                ArrayList data = msg.getData().getParcelableArrayList("data");
                PersonBean o = (PersonBean) data.get(0);
                Log.e("MyLog", "MainActivity.handleMessage:  personBean.getName() --->>> " + o.getName() + "  personBean.getAge()  " + o.getAge());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PersonBean p = new PersonBean("zhan_san", 18);
        Bundle bundle = new Bundle();
        ArrayList arr = new ArrayList();
        arr.add(p);
        bundle.putStringArrayList("data",arr);
        Message message = new Message();
        message.what = 111;
        message.setData(bundle);
        handler.sendMessage(message);
    }
}
成功打印
E/MyLog: MainActivity.handleMessage:  personBean.getName() --->>> zhan_san  personBean.getAge()  18
相关标签: handler