问题
I'm trying to create an onCheckedChanged Listener for my RadioGroup, but eclipse is throwing erros at me. this is the code
rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("chk", "id" + checkedId);
if (checkedId == R.id.switchToFriends) {
// some code
} else if (checkedId == R.id.switchToUsers) {
// some code
}
}
});
And from eclipse I get an error on setOnCheckedChangeListener
suggesting to change it to setOnClickListener/setOnDragListener, and others.
On new OnCheckedChangeListener()
it tells me to add unimplemented methods, and when I select that option it adds this :
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
}
So I end up with this:
rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("chk", "id" + checkedId);
if (checkedId == R.id.switchToFriends) {
// some code
} else if (checkedId == R.id.switchToUsers) {
// some code
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
}
});
And it tells me to remove the @Override
annotation from the method that I wrote.
Anyone knows why it won't let me override the method that way? I've checked the android docs and the method it shows there uses the format that I try to override
回答1:
Make sure you imported the correct package import android.widget.RadioGroup.OnCheckedChangeListener;
then the @Override
will be correct
回答2:
You can directly add the listener with the ClassName
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
}
});
If, for example, you already are using a CompoundButton and associated OnCheckedChangeListener, you will not be able to import the RadioGroup class, but will still be able to access it directly using this solution.
回答3:
I think you have imported the wrong package.
You should import
android.widget.RadioGroup.OnCheckedChangeListener
instead of
android.widget.CompoundButton.OnCheckedChangeListener
来源:https://stackoverflow.com/questions/19654404/i-cant-create-an-oncheckedchanged-listener-for-my-radiogroup