我有一个简单的安卓应用程序,我想在其中获取用户输入(字符串)。所以我有一个“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/