我試着創建一個公共類來嘗試從一個活動向另一個活動傳輸數據。但是當我嘗試設置這個類的信息時,我設法得到Int變量而不是String,並且當我試圖獲取這些數據時它是空白的。我將如何使用公共課程將數據從一項活動轉移到另一項活動?
這是我的MainActivity
public void toyota_yaris(View view) {
CurrentCar currentcar = new CurrentCar();
currentcar.setInfo("Toyota Yaris",130,8,1160,7);
Intent switchScreen = new Intent(MainActivity.this,CarActivity.class);
MainActivity.this.startActivity(switchScreen);
}
這是我的CarActivity
CurrentCar currentcar = new CurrentCar();
TextView name = (TextView) findViewById(R.id.name);
name.setText(currentcar.getName());
TextView speed = (TextView) findViewById(R.id.speed);
speed.setText(String.valueOf(currentcar.getSpeed()));
這是我的CurrentCar類(getter和setter類)
public class CurrentCar {
private String mName;
private int mSpeed;
private int mAge;
private int mMileage;
private int mSeats;
public void setInfo(String Name,int Speed,int Age,int Mileage,int Seats) {
mName = Name;
mSpeed = Speed;
mAge = Age;
mMileage = Mileage;
mSeats = Seats;
}
public String getName() {
return mName;
}
public int getSpeed() {
return mSpeed;
}
public int getAge() {
return mAge;
}
public int getMileage() {
return mMileage;
}
public int getSeats() {
return mSeats;
}
}
正在創建的對象可以使用辛格爾頓,讓您的CurrentCar類的靜態和看得見的CarActivity。或者您可以實施parcelable以在活動之間傳遞您的汽車物件。希望能幫助到你 –