【发布时间】:2017-03-17 17:51:09
【问题描述】:
我的 Activity 中有这个切换按钮,指示打开(如果为真)或关闭(如果为假)。我实现了一个 setOnCheckedChangeListener 方法来在我的数据库中更改切换按钮的状态。
在我的这部分代码中,当有人点击它时,我会更改切换按钮的状态:
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(TabLayoutScreenActivity.this);
alertDialog.setMessage("Have you updated today's menu?");
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
callServiceToOpenBistro();
Toast.makeText(getApplicationContext(), "Your Bistro is now open", Toast.LENGTH_SHORT).show();
OpenClose.setText("Open");
mySwitch.setChecked(true);
dialog.cancel();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Please updated in order to open your Bistro", Toast.LENGTH_SHORT).show();
OpenClose.setText("Closed");
mySwitch.setChecked(false);
dialog.cancel();
}
});
alertDialog.show();
} else {
callServiceToOpenBistro();
OpenClose.setText("Closed");
}
}
});
在我的这部分代码中,如果存储在我的数据库中的关于切换按钮的数据是真还是假(打开或关闭),我会检查我的数据库:
private void callServiceToCheckStatus() {
new VolleyHelper(this).get("current_status/" + PrefernceHelper.getString(this, Commons.Constants.USER_ID), null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("bistro_status");
String status = "",flag = "",opHours = "";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
status = jsonObject.getString("status");
}
if (status.equals("Online")){
OpenClose.setText("Open");
mySwitch.setChecked(true);
} else if (status.equals("Offline")){
OpenClose.setText("Closed");
mySwitch.setChecked(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
}
问题在于,在 callServiceToCheckStatus 方法中,在获取数据库中的状态后,我将切换按钮更改为 true(如果它已经打开)或 false(如果它存储为 Closed)。但是当我使用“setChecked”时,它会调用“setOnCheckedChangeListener”方法。这不是我真正想要的。
有没有办法以不同的方式做到这一点?在不调用 setOnCheckedChangeListener 的情况下更改切换按钮的状态,或者可能使用一个侦听器来检查切换是否被单击而不是检查其状态是否更改 (setOnCheckedChangeListener)?
【问题讨论】:
标签: android toggle android-togglebutton