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