我想将一个int从FirstActivity传递给TheAdapter(不是一个活动)。当在FirstActivity中单击一个按钮时,它会打开SecondActivity,它创建一个TheAdapter实例,在列表视图中显示其内容。
FirstActivity:
viewBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
number = 5; //this is an integer
Intent in = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(in);
}
});
SecondActivity:
TheAdapter adapter = new TheAdapter(this, 0);
myListView.setAdapter(adapter);
我想从FirstActivity获取整数,所以我可以在TheAdapter中使用它。
答案 0 :(得分:0)
第一项活动:
viewBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
number = 5; //this is an integer
Intent in = new Intent(FirstActivity.this, SecondActivity.class);
in.putExtra("name of your value (eg. adapter_int)", number);
startActivity(in);
}
});
第二项活动:
Intent intent = getIntent();
int yourInt = intent.getExtra("name of your value (eg. adapter_int)", 0); // 0 is a default value
答案 1 :(得分:0)
Intent in = new Intent(FirstActivity.this, SecondActivity.class);
in.putExtra(Key , value);
startActivity(in);
//在SecondActivity中
Bundle bundle = this.getIntent().getExtras();
//for example int param
int param = 0;
if(bundle == null){
Log.e(TAG, "bundle is null.");
}else{
param = bundle.getInt(key);
}
如果你想要传递对象(可序列化对象)它应该是有用的
public class Serializer {
public static byte[] serialize(Object obj) throws IOException {
try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
try(ObjectOutputStream o = new ObjectOutputStream(b)){
o.writeObject(obj);
}
return b.toByteArray();
}
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
try(ObjectInputStream o = new ObjectInputStream(b)){
return o.readObject();
}
}
}
}