需要在activity之間傳遞數據,遇到一些困難。
代碼:
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
ArrayList<String> players = new ArrayList<String>();
Intent zacniIgro = getIntent();
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
players.add(text);
zacniIgro.putStringArrayListExtra("players", players);
return newTextView;
}
public void zacniIgro (View v){
Intent zacniIgro = new Intent (getApplicationContext(), Igra.class);
startActivity(zacniIgro);
}
在新的activity中如何得到數據?我試過:
ArrayList<String> players = data.getStringArrayListExtra("players");
檢索列表:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_igra);
ArrayList<String> players = data.getStringArrayListExtra("players");
}
給data加了紅下劃線。不知道是什麼錯誤。
因為你每次開始activity都創建了一個intent。
ArrayList<String> players = new ArrayList<String>(); //declare it outside of the function
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
players.add(text);
return newTextView;
}
public void zacniIgro (View v){
Intent zacniIgro = new Intent (getApplicationContext(), Igra.class);
zacniIgro.putStringArrayListExtra("players", players);
startActivity(zacniIgro);
}
在另一個activity中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_igra);
Intent data = getIntent();
ArrayList<String> players = data.getStringArrayListExtra("players");
}