在Android中有一个edittext在你编辑后,我们需要获取他的字数,以每一天为一个周期,算出这天内更新的字数
时间: 2024-05-07 21:22:50 浏览: 12
你可以通过监听EditText的文本变化来实现:
1. 在EditText的onCreate方法中添加文本变化监听器:
```
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// 在EditText中的文本变化前回调,不需要实现
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 在EditText中的文本变化时回调
// 在这里统计字数
int currentWordCount = s.length();
// 将字数保存到SharedPreferences中
SharedPreferences sharedPreferences = getSharedPreferences("word_count", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("current_word_count", currentWordCount);
editor.apply();
}
@Override
public void afterTextChanged(Editable s) {
// 在EditText中的文本变化后回调,不需要实现
}
});
```
2. 在你需要显示当天更新字数的地方,获取SharedPreferences中保存的字数并计算:
```
// 获取SharedPreferences中保存的字数
SharedPreferences sharedPreferences = getSharedPreferences("word_count", MODE_PRIVATE);
int currentWordCount = sharedPreferences.getInt("current_word_count", 0);
// 获取今天的日期
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String today = dateFormat.format(new Date());
// 获取SharedPreferences中保存的今天更新的字数
int todayWordCount = sharedPreferences.getInt(today, 0);
// 计算今天新增的字数
int newWordCount = currentWordCount - todayWordCount;
// 将今天更新的字数保存到SharedPreferences中
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(today, currentWordCount);
editor.apply();
// 显示今天新增的字数
textView.setText("今天新增的字数为:" + newWordCount);
```
这样就可以实现获取EditText中的字数,并在每天结束时计算当天新增的字数了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)