对于setOnCheckedChangeListener和buttonView,Android“无法解析符号”

时间:2017-06-07 12:53:56

标签: java android togglebutton

我正在尝试创建一个开关,当启用时会隐藏一个名为button的按钮,但它会返回SetOnCheckedChangeListener和buttonView的错误,其中显示Cannot resolve symbol

package com.jordthedev.firstapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    int count = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    public void switchActivity(View v){
        startActivity(new Intent(MainActivity.this, SecondActivity.class));
    }

    ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                toggle.setVisibility(toggle.INVISIBLE);
            } else {
                toggle.setVisibility(toggle.VISIBLE);
            }
        }
    });

}

2 个答案:

答案 0 :(得分:1)

也许你必须将ToggleButton放在onCreate()方法上试试上面的代码

package com.jordthedev.firstapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    int count = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    toggle.setVisibility(toggle.INVISIBLE);
                } else {
                    toggle.setVisibility(toggle.VISIBLE);
                }
            }
        });
    }


    public void switchActivity(View v){
        startActivity(new Intent(MainActivity.this, SecondActivity.class));
    }



}

答案 1 :(得分:1)

  

将此OnCheckedChangeListener代码替换为此

ToggleButton toggle =(ToggleButton) findViewById(R.id.toggleButton);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    toggle.setVisibility(toggle.INVISIBLE);
                } else {
                    toggle.setVisibility(toggle.VISIBLE);
                }
            }
        });