public class MainActivity extends Activity implements OnCheckedChangeListener {
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb = (ToggleButton) findViewById(R.id.toggleButton1);
img = (ImageView) findViewById(R.id.imageView1);
tb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
// TODO Auto-generated method stub
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ToggleButton
android:checked="false"
android:textOn="开"
android:textOff="关"
android:id="@+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/off" />
这个MainActivity和setOnCheckedChangeListener错了,我是照着视频打得,不知道为什么错了。