Handler 전달 객체

3770 단어 code
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

좋은 웹페이지 즐겨찾기