java - 如何使用widget.switch更改editText值Android

标签 java android switch-statement

我有一个 widget.switch,我试图让它根据开关的值将特定数字除以二(或乘以二)。

这基本上是我所拥有的内容,出于隐私原因进行了编辑:

在onCreate中:

theSwtch = (Switch)findViewById(R.id.theSwtch);
theSwtch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (theSwtch.isChecked()){theSwtch.setText("Weekly"); switcher = true;}
        else if (!theSwtch.isChecked()){theSwtch.setText("Bi-Weekly"); switcher = false;}
        // do something, the isChecked will be
        // true if the switch is in the On position
    }
});

并在 OnClick 中:

public void onClick(View view) {
    Double someNumber = Double.parseDouble(editTextInput.getText().toString());
    if (view.getId() == theSwitch.getId()){
        if (!theSwitch.isChecked()) {
            someNumber = someNumber/2;
            editTextInput.setText(someNumber.toString());
        } else if (wklySwtch.isChecked()) {
            someNumber = someNumber*2;
            editTextInput.setText(someNumber.toString());
        }
        if (view.getId() == btnCalculate.getId()) {
            outPut.setText(someNumber.toString());
        }
    }
}

最佳答案

从 OnClickListener 中删除除法或乘法的逻辑,而是在 OnCheckedChangeListener 中完成整个操作:

    theSwtch = (Switch)findViewById(R.id.theSwtch);
    theSwtch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            Double someNumber = Double.parseDouble(editTextInput.getText().toString());
            if (theSwtch.isChecked()){
                theSwtch.setText("Weekly"); 
                switcher = true;
                someNumber = someNumber/2;
                editTextInput.setText(someNumber.toString());
            } else if (!theSwtch.isChecked()) {
                theSwtch.setText("Bi-Weekly"); 
                switcher = false;
                someNumber = someNumber*2;
                editTextInput.setText(someNumber.toString());
            }
                // do something, the isChecked will be
               // true if the switch is in the On position
        }
    });

关于java - 如何使用widget.switch更改editText值Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47372770/

相关文章:

java - 为什么我的 switch 语句不起作用并陷入无限循环?

java - Maven ArtifactNotFoundException 故障排除

java - 如何在帮助程序中将映射添加到现有的动态类型 - EclipseLink

android - 如何让移动网站的访问者离线访问 CouchDB 数据?

android - 创建新的 GoogleApiClient 时状态代码 16

c++ - switch case 语句不起作用?

c - 为什么在这个 switch 语句中匹配 default 大小写?

java - 为什么在 JSTL el 表达式中转义引号时出现 JSP 错误 "attribute for "未正确终止?

java - CardView-TextView marginRight

android - 使用 Itemtouchhelper 更改房间数据库的顺序