android - 字符串变量在 setOnClickListener() 函数之外变为空

标签 android string android-studio

我有一个简单的安卓应用程序,我想在其中获取用户输入(字符串)。所以我有一个“EditText”框和一个“Enter”按钮。当用户键入内容并按下 Enter 键时,我会尝试显示该文本,只要我在“setOnClickListener()”函数中执行所有操作,它就会正常工作。字符串变量在函数外变为空。这是我的代码:

public class MainActivity extends AppCompatActivity {

 Button hitButton;
 EditText userInput;
 String myVariable;

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

    hitButton = (Button)findViewById(R.id.button);
    hitButton.setOnClickListener(new View.OnClickListener() {
      @Override
       public void onClick(View view) {
          userInput = (EditText)findViewById(R.id.userInput);
          myVariable= userInput.getText().toString();

       }
    });

     TextView textView = (TextView)findViewById(R.id.textView);
     textView.setText(myVariable); // THIS IS THE PROBLEM
     // IT DISPLAYS NULL WHICH MEANS THAT String myVariable = null
     }
  }

如果我将 TextView.setText(myVariable) 放在 setOnClickListener 函数中,那么它可以正常工作,但在函数之外,myVariable 变为空。我需要在函数外部使用该变量。

提前致谢:)

最佳答案

如果你想要它在 onClick 方法之外,像这样使用 SharedPreferences

public class MainActivity extends AppCompatActivity {

 Button hitButton;
 EditText userInput;
 String myVariable;
 public static final String MyPREFERENCES = "MyPrefs" ;
 public static final String KEY = "Key";
 SharedPreferences sharedpreferences;

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

    hitButton = (Button)findViewById(R.id.button);

    sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);        

    hitButton.setOnClickListener(new View.OnClickListener() {
      @Override
       public void onClick(View view) {
          userInput = (EditText)findViewById(R.id.userInput);
          myVariable= userInput.getText().toString();

          SharedPreferences.Editor editor = sharedpreferences.edit();
          editor.putString(KEY, myVariable);
          editor.commit();
       }
    });

     TextView textView = (TextView)findViewById(R.id.textView);
     textView.setText(sharedpreferences.getString(KEY, null)); // THIS IS THE PROBLEM
     // IT DISPLAYS NULL WHICH MEANS THAT String myVariable = null
     }
  }

希望对你有帮助

关于android - 字符串变量在 setOnClickListener() 函数之外变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164140/

相关文章:

android - 带有 Android Studio 的 Cordova webview(找不到文件 :///android_asserts/www/index. html)

sql - Oracle 10g 中的 REPLACE 没有按我的预期工作,有人能解释一下吗?

java - 我无法打开我的类,只能找到一个 BuildConfig 文件

android-studio - IntelliJ IDEA 和 Atom 编辑器中的相同键盘映射

android - 在 android 中显示对话框时处理返回键

android-如何在所有内容之上进行布局而不透明

java - 如何根据自定义标准保持排序的数据结构

Java - 在不知道字符编码的情况下将 byte[] 转换为 String

javascript - 如何使用 javascript 分隔这些字符串

android-studio - Android Studio 哪里是 Flutter 插件的颜色选择器