簡體   English   中英

將數據傳遞到另一個活動

[英]Passing data to another 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);
}

現在如何獲得新活動中的數據? 我試過了但是沒用

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");
}

紅色強調了“數據”,因此我很確定“數據”有問題嗎?

問題是您在開始新活動時正在創建新的意圖。 嘗試這個 :

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);
}

在其他活動上:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_igra);
    Intent data = getIntent();
    ArrayList<String> players = data.getStringArrayListExtra("players");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM