是的,Android Activity可以傳遞數據。在Android中,可以使用Intent對象在不同的Activity之間傳遞數據。以下是一些常見的數據傳遞方法:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("key", value); // key為字符串類型,value為要傳遞的數據
startActivity(intent);
在SecondActivity中,可以通過以下方式獲取傳遞的數據:
String value = getIntent().getStringExtra("key");
public class MyParcelable implements Parcelable {
private int data;
private String text;
// 構造函數、getter和setter方法省略
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(data);
dest.writeString(text);
}
public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() {
@Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
@Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
然后,在FirstActivity中,將MyParcelable對象傳遞給SecondActivity:
MyParcelable myParcelable = new MyParcelable();
myParcelable.setData(1);
myParcelable.setText("Hello");
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("parcelable_key", myParcelable);
startActivity(intent);
在SecondActivity中,可以通過以下方式獲取傳遞的MyParcelable對象:
MyParcelable myParcelable = getIntent().getParcelableExtra("parcelable_key");
ArrayList<String> list = new ArrayList<>();
list.add("item1");
list.add("item2");
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("serializable_key", list);
startActivity(intent);
在SecondActivity中,可以通過以下方式獲取傳遞的ArrayList:
ArrayList<String> list = getIntent().getSerializableExtra("serializable_key");