android - 如何从编辑文本中获取字符串并传递给新活动?
问题描述
我正在尝试收集用户输入并将其传递给另一个活动并使用文本视图显示它。
我尝试使用 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);
}
我希望输出几句话来显示用户输入的单词的故事,但相反,我得到的输出如下图所示:
解决方案
您可以使用下面的代码在名为MainActivityOut.class的另一个活动中检索您的字符串,并将该字符串传递给您的文本视图。
String madLib = getIntent().getStringExtra("story");
yourTextView.setText(madLib);
推荐阅读
- javascript - 如何获取这个内联函数并将其转换为方法,同时保留对此的访问权限?
- java - 从云端启动 jmeter 分布式测试
- c++ - 在我的 strpbrk 函数中返回 nullptr 时出现分段错误
- python - 为什么是错的
- javascript - 使用 javascript/react 按内部键过滤
- python - 如何进行嵌套列表理解?
- terraform - Terraform 变量定义
- python - 如何使用 pandas 聚合大型 DataFrame 中的多个列?
- spring-boot - 如何在 springboot 客户端应用程序中创建不共享底层网络连接的 rSockets
- elasticsearch - 在热门点击聚合中访问脚本排序上下文中的字段