Reputation: 314
I am new to android programming and i got this from the developer website on how to properly implement this. However when i copy and pasted this into android studio it could not resolve setOnClickListener, setOnCheckedChangeListener, and buttonView.
This is my first time working with toggle buttons and buttons in android and i did a lot of searching about on here before i broke down to ask this. This is a separate button class outside of MainInterface do i need to extend or implement anything special or import anything?
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class Button extends MainInterface {
ToggleButton toggle = (ToggleButton) findViewById(R.id.BeaconButton);
toggle.setOnClickListener(new CompoundButton.OnCheckedChangeListener());
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
}
Also what is the difference between the above code and the following code. would the following code be applicable for setting listeners?
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// do something
}
} else {
// set as it was
}
}
Upvotes: 1
Views: 3465
Reputation: 34360
Use this method..
this.someToggleButton = (ToggleButton)findViewById(R.id.someToggleButton) ;
this.someToggleButton.setOnCheckedChangeListener( new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked)
{
doSomethingWith(toggleButton, isChecked) ;
}
}) ;
Upvotes: 0
Reputation: 26198
The setOnClickListener
does not accepts CompoundButton.OnCheckedChangeListener()
as a listener thus giving you compile time error.
The method signature for setOnClickListener
setOnClickListener(View.OnClickListener l)
solution:
Use the default View.OnClickListener
listener for views to be set in your ToggleButton
toggle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Upvotes: 2