首页 > 解决方案 > 如何从编辑文本中获取字符串并传递给新活动?

问题描述

我正在尝试收集用户输入并将其传递给另一个活动并使用文本视图显示它。

我尝试使用 getText() 和 toString() 函数并传递意图,但是在运行程序时,应该包含用户输入的字符串没有正确显示。

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_in);

            //Collect user inputs and store them in strings
            noun1 = (EditText)findViewById(R.id.noun1);
            pluralNoun =  (EditText)findViewById(R.id.pluralNoun);
            noun2 = (EditText)findViewById(R.id.noun2);
            place = (EditText)findViewById(R.id.place);
            adjective = (EditText)findViewById(R.id.adjective);
            noun3 = (EditText)findViewById(R.id.noun3);

            firstNoun = noun1.getText().toString();
            nounPlural = pluralNoun.getText().toString();
            secondNoun = noun2.getText().toString();
            inputPlace = place.getText().toString();
            inputAdjective = adjective.getText().toString();
            thirdNoun = noun3.getText().toString();

            madLib ="Be kind to your " + firstNoun + "-footed " + pluralNoun + "\n" +
                    "For a duck may be somebody`s " + secondNoun + ",\n" +
                    "Be kind to your " + pluralNoun + " in " + inputPlace + "\n" +
                    "Where the weather is always " + inputAdjective + ".\n" +
                    "\n" +
                    "You may think that this is the " + thirdNoun + ",\n" +
                    "Well it is.\t";

        }



        public void createStory(View view) {
            Intent myIntent = new Intent(MainActivityIn.this,
                    MainActivityOut.class);
            myIntent.putExtra("story",madLib);
            startActivity(myIntent);
        }

我希望输出几句话来显示用户输入的单词的故事,但相反,我得到的输出如下图所示:

实际输出

标签: androidandroid-edittext

解决方案


您可以使用下面的代码在名为MainActivityOut.class的另一个活动中检索您的字符串,并将该字符串传递给您的文本视图。

String madLib = getIntent().getStringExtra("story");
yourTextView.setText(madLib);

推荐阅读