2.设计按钮响应代码,保存按钮界面输入信息保存于Shared Preference共享文件 3.退出应用程序或关机时自动保存界面信息到共享文件
时间: 2024-05-09 10:21:54 浏览: 16
好的,您的第一个问题是如何设计按钮响应代码,并将界面输入信息保存到共享文件中。以下是一个简单的示例代码:
```
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = findViewById(R.id.edit_text);
mSharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
Button saveButton = findViewById(R.id.save_button);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inputText = mEditText.getText().toString();
mEditor.putString("inputText", inputText);
mEditor.apply();
Toast.makeText(MainActivity.this, "Input Saved!", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onStop() {
super.onStop();
String inputText = mEditText.getText().toString();
mEditor.putString("inputText", inputText);
mEditor.apply();
}
}
```
在这个例子中,我们首先在 `onCreate()` 方法中初始化了界面上的输入框和SharedPreferences文件。接下来,我们设置保存按钮的点击监听器,在按钮被点击后,将输入文本保存到SharedPreferences文件中,同时也弹出一个提示信息让用户知道信息已经成功保存。最后,我们重写了 `onStop()` 方法,在应用程序停止运行时自动保存输入文本。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![xml](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)