【发布时间】:2025-12-31 15:10:06
【问题描述】:
我将按钮的状态存储在共享首选项中,它似乎可以工作。我正在使用按钮打开服务。如果我打开服务并离开应用程序,我可以再次按下按钮将其关闭,这很好。唯一的事情是,当我打开服务时,按钮中的文本应更改为“停止服务”并且确实如此,但是当我退出应用程序时,它会更改回“启动服务”但状态已保存。这是我正在实施的地方
SharedPreferences prefs = Home.this.getActivity().getSharedPreferences("check", MODE_PRIVATE);
final String check_state = prefs.getString( "state", "default");
holder.startsCar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(check_state.equals("false")){
holder.startsCar.setText("Stop Car");
Intent i = new Intent(Home.this.getActivity(), MQTTService.class);
ContextCompat.startForegroundService(Home.this.getActivity(), i);
for (int j = 0; j < adapter.getItemCount(); j++) {
if (adapter1.getItem(j).isSelected(true)) {
name = ((TextView) holder.itemView.findViewById(R.id.make)).getText().toString();
Toast.makeText(getActivity(), "Data Inserted....." + name, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
SharedPreferences.Editor editor = Home.this.getActivity().getSharedPreferences("check", MODE_PRIVATE).edit();
editor.putString("state", "true");
editor.apply();
adapter.notifyDataSetChanged();
//Toast.makeText(Home.this.getContext(), "Service Started", Toast.LENGTH_SHORT).show();
}else{
holder.startsCar.setText("Start Car");
Intent i = new Intent(Home.this.getActivity(), MQTTService.class);
getActivity().stopService(i);
Toast.makeText(Home.this.getContext(), "Service Stoped", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = Home.this.getActivity().getSharedPreferences("check", MODE_PRIVATE).edit();
editor.putString("state", "false");
editor.apply();
adapter.notifyDataSetChanged();
}
}
});
为什么会发生这种情况?
【问题讨论】:
-
您在单击时存储按钮的状态,这完全没问题,但您缺少的是您需要根据您当前缺少的 sharedprefs 值再次设置文本
-
感谢您的回复。我已经很久没有使用共享偏好了。如何根据 prefs 值实现它?
-
我已经写了答案检查,如果有帮助请告诉我...
标签: android android-recyclerview sharedpreferences