关于Activity之间传递List<T>,一直以来没有时间去尝试,关于各种说法层出不穷,
1.Activity里面存静态变量,直接类名点获取.
2.Application里面设置一个属性,公开方法取什么的。
今天我们来看看另一种传法:
1.先看效果:
我们需要传的list里面的对象Bean.java的代码:
package com.example.intentlist;
import java.io.Serializable;
public class Bean implements Serializable {
private int id;
private String name;
private int age;
public Bean() {
}
public Bean(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
MainActivity.java的代码:
package com.example.intentlist;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
List<Bean> lstBean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstBean = new ArrayList<Bean>();
Bean bean = new Bean(1, "张三", 12);
lstBean.add(bean);
Bean bean1 = new Bean(2, "李四", 13);
lstBean.add(bean1);
Bean bean2 = new Bean(3, "王五", 14);
lstBean.add(bean2);
Bean bean3 = new Bean(4, "赵六", 15);
lstBean.add(bean3);
((Button) findViewById(R.id.btn_next)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intentPut = new Intent(MainActivity.this, IntentTestActivity.class);
intentPut.putExtra("lstBean", (Serializable) lstBean);
startActivity(intentPut);
}
});
}
}
package com.example.intentlist;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class IntentTestActivity extends ActionBarActivity {
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_test);
Intent intentGet = getIntent();
List<Bean> lstBean = (List<Bean>) intentGet.getSerializableExtra("lstBean");
String result = "IntentTestActivity" + "\n";
for (Bean bean : lstBean) {
result += bean.getId() + "---" + bean.getName() + "---" + bean.getAge() + "\n";
}
((TextView) findViewById(R.id.tv_result)).setText(result);
}
}
源码————> IntentList.zip