问题
I'm trying to create a switch which when enabled hides a button called button
but it returns an error for SetOnCheckedChangeListener and buttonView which says 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);
}
}
});
}
回答1:
Maybe you have to place ToggleButton in onCreate() method try above code
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));
}
}
回答2:
Replace your
OnCheckedChangeListener
Code with this
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);
}
}
});
来源:https://stackoverflow.com/questions/44413251/android-cannot-resolve-symbol-for-setoncheckedchangelistener-and-buttonview