在很多情况下,调用startActivity(Intent) 方法,跳转到另外一个Activity或其他component,需要传递一个对象给它。
可以让这个要传递的对象所属类实现Serializable或者Parcelable接口。然后利用onCreate函数中的Bundle参数作为载体,传递这个对象。在新的组件中再获得即可。
例如:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ListViewAdapter(this);
listView.setAdapter(adapter);
adapter.refresh();
listView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
Item item = (Item) adapter.getItem(position);
Intent intent = new Intent(ListViewDemo01Activity.this,DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("item", item);
intent.putExtras(bundle);
startActivity(intent);
Log.v("tag","===============selected ");
}
});
}
在接收对象的地方:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
Item item = (Item) getIntent().getSerializableExtra("item");
findViewById(R.id.imageView).setBackgroundResource(item.getImage());
TextView title = (TextView) findViewById(R.id.title);
TextView contentTextView = (TextView) findViewById(R.id.content);
title.setText(item.getTitle());
contentTextView.setText(item.getContent());
}