使用意图将字符串发送到新活动

时间:2013-09-18 21:56:11

标签: android android-intent android-activity

我是Android的新手,我正在尝试学习如何使用意图来启动新活动并向其发送字符串。有人可以告诉我为什么这不起作用:

package com.example.experimentingwithactivities;

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

public class MainActivity extends Activity {

    TextView View;
    String String1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void onButton1Click (View v) {
        String morestuff  = "Something";

        Intent i = new Intent(this, other_activity.class);
        i.putExtra("stuff", morestuff);
        startActivity(i); 
    }

}

这是第二项活动

package com.example.experimentingwithactivities;

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

public class other_activity extends Activity{
    TextView something;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seccond_activity);

        something = (TextView) findViewById (R.id.textView1);

        Intent intent = getIntent();
        String morestuff = intent.getStringExtra("stuff");

        something.setText(morestuff);
    }
}

每当我运行它时,它会意外停止。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先尝试这样:

    TextView something;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seccond_activity);

        Intent intent = getIntent();
        String morestuff = intent.getStringExtra("stuff");

        //comment this out if it does not crash
        //something = (TextView) findViewById (R.id.textView1);
        //something.setText(morestuff);
}

如果崩溃,则表示textView1不属于seccond_activity.xml,请将其重命名为someting_textview1