ToggleButton的用法

XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ToggleButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toggleButton"
        android:textOff=""
        android:textOn=""/>

    <ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView2"
        android:background="@drawable/a1"/>

</LinearLayout>
MainActivity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity implements CompoundButton.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.toggleButton);
        //设置监听器
        tb.setOnCheckedChangeListener(this);
       //初始化控件
  img = (ImageView) findViewById(R.id. imageView2); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { img.setBackgroundResource(isChecked?R.drawable. a2:R.drawable. a1); }}

猜你喜欢

转载自blog.csdn.net/YYLong0/article/details/71426119