【发布时间】:2017-10-30 15:17:13
【问题描述】:
我正在开发一个 android 应用程序,其中用户按下按钮,生成文本,然后有一个菜单选项来共享/导出文本。
以下是相关代码部分(为清楚起见,我没有粘贴整个代码,但如果您需要任何内容,请告诉我)
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String savedText = SomeMethod(); //the string used here is obtained through another method
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
}
});
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_export) {
exportPage();
return true;
}
return super.onOptionsItemSelected(item);
}
public void exportPage() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, savedText);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
我的问题:
我怎样才能真正将 SomeMethod 方法生成的字符串(即 savedText,见代码第 5 行的注释)发送到 exportPage 方法?就目前而言,代码从初始化的字符串值中获取 savedText 字符串的值,而不是 SomeMethod 方法生成的值。
我尝试过的: 在寻找类似问题的答案时,我发现这里描述的一种方法是:How to pass a string from one method to another method in Java
我尝试相应地修改我的代码,如下所示:
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
exportPage(); // <<< attempting to send the string to the exportPage method
public void exportPage() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, this.savedText); //<<< modified
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
但这给了我保存的文本字符串未初始化的错误。我尝试初始化它,但现在它再次使用该全局值而不是修改后的值。
此时我想也许我正在使用局部变量而不是实例变量(我是一个真正的初学者,所以我仍在学习这些方面),并尝试了另一种方式:
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
exportPage(savedText); // <<< attempting to send the string to the exportPage method
public void exportPage(String savedText) { //<<<< modified
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, savedText);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
但现在又出现了一个错误。在选择菜单项的代码部分:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_export) {
exportPage();
return true;
}
return super.onOptionsItemSelected(item);
我收到一个错误,因为 exportPage 方法需要一个字符串。我试图用exportPage(savedText); 修改它,但当然现在它无法识别字符串 savedText 并希望我初始化它(这样做,我回到原来的问题,获取全局字符串值而不是生成的) .
正如我所说,我是一个初学者,所以我确信这是一个非常简单的错误,但我就是想不通。有什么想法吗?
【问题讨论】:
标签: java android string methods