qq_42660156
追忆~似水年华
2020-03-17 18:31
采纳率: 48%
浏览 362

Android Studio中Activity之间为什么无法传送数据?

Main1Activity、Main2Activity可以互相跳转,但Main1Activity无法向Main2Activity传送数据。

在Main1Activity中直接这样写bundle.putString("snameText", string),在Main2Activity中可以接收数据。

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;

public class Main1Activity extends ActionBarActivity {

    private Intent intent = new Intent();
    private Bundle bundle = new Bundle();//新建Bundle

    private EditText snameText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        snameText = (EditText) findViewById(R.id.snameText);

        bundle.putString("snameText", snameText.getText().toString());

    }

    public void confirmMain1(View v) {
        intent.setClass(Main1Activity.this, Main2Activity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

}





import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class Main2Activity extends Activity {

    private Intent intent = new Intent();
    private Bundle bundle = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        bundle = this.getIntent().getExtras();

        String snameText = bundle.getString("snameText");
        TextView snameView = (TextView) findViewById(R.id.snameView);
        snameView.setText(snameView.getText().toString() + snameText.toString());
    }

    public void returnMain2(View v) {
        intent.setClass(Main2Activity.this, Main1Activity.class);
        startActivity(intent);
    }

}


新手不是很会

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

1条回答 默认 最新

  • weixin_37619588
    一个奇奇怪的 2020-03-18 11:22
    已采纳

    public void confirmMain1(View v) {
    intent.setClass(Main1Activity.this, Main2Activity.class);
    bundle.putString("snameText", snameText.getText().toString());
    intent.putExtras(bundle);
    startActivity(intent);
    }
    snameText.getText().toString()在onCreate当然没数据,因为这时候activity才初始化,你还没在editText中填入数据

    点赞 评论

相关推荐