如何在以下代码中使用setChecked方法

时间:2015-02-14 20:45:48

标签: android android-layout android-activity

我有这段代码

Switch serviceSwitch;
serviceSwitch =(Switch) this.findViewById(R.id.switchservice);
serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() 
{

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {


        if(isChecked)
        {
            arrayChecking();
            serviceSwitch.setChecked(false);             
        }
    }
}

 public void arrayChecking()
{

    if(tbPreferenceArray.length>0)
    {

        Toast.makeText(getApplicationContext(), "Please Set the Time and Day", Toast.LENGTH_LONG).show();



        }
    else
    {
         Intent i = new Intent(MainActivity.this, TimerService.class);
         MainActivity.this.startService(i);
         Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_LONG).show();  
    }
}

从代码中,当用户打开交换机时,arrayChecking()的方法调用将执行,并且还有代码将交换机重置为(false),但此代码无效,{{1 }} 不管用。任何人都可以帮我解决这个简单的问题吗?对不起,语言

1 个答案:

答案 0 :(得分:0)

稍微修改一下arrayChecking方法:

public void arrayChecking(){
    if(tbPreferenceArray.length>0){
        Toast.makeText(getApplicationContext(), "Please Set the Time and Day", Toast.LENGTH_LONG).show();
        //Add this to set the Switch checked to false
        serviceSwitch.setChecked(false); 
    }
    else{
         Intent i = new Intent(MainActivity.this, TimerService.class);
         MainActivity.this.startService(i);
         Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_LONG).show();  
    }
}

从您的serviceSwitch.setChecked(false);方法移除onCheckedChanged

serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() 
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {
        if(isChecked)
        {
            arrayChecking();             
        }
    }
}