Android: When using setOnCheckedChangeListener on switches I get 'Cannot Resolve Symbol Error'

帅比萌擦擦* 提交于 2019-12-04 11:01:49
Mohit Rajput

You have to initialize Switch inside onCreate()

move

  Switch swi = (Switch) findViewById(R.id.swch);
  swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) //Line A
        {

        }
    });

in onCreate. You can't call findViewById, before the activity is created, and swi.setOnCheckedChangeListener(..); is not a valid statement

Replace the below code

        switchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SwitchButton switchButton = (SwitchButton)view;

by

        switchButton.setOnCheckedChangeListener( new SwitchButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SwitchButton switchButton = (SwitchButton) buttonView;

it will work !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!