DaffodilGirl 2013-07-08 08:12 采纳率: 0%
浏览 2336
已采纳

传递数据到另一个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");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog