DaffodilGirl
2013-07-08 08:12
采纳率: 78.1%
浏览 2.3k

传递数据到另一个activity

需要在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加了红下划线。不知道是什么错误。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • abcdeFGh_xyz 2013-07-08 09:29
    已采纳

    因为你每次开始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");
    }
    
    点赞 打赏 评论
  • JaveZh 2013-07-08 08:49

    你的data申明在哪里??

    点赞 打赏 评论

相关推荐 更多相似问题