手记

使用ToggleButton按钮实现开关

ToggleButton特有属性:
android:textOff="@string/toggleoff_name"
android:textOn="@string/toggleoon_name"
android:checked="true" 代表开

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{
    private ToggleButton tb;
    private ImageButton img;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.toggle);

        tb = (ToggleButton) findViewById(R.id.toggleButton);
        img = (ImageButton) findViewById(R.id.imageButton);

        //设置监听器
        tb.setOnCheckedChangeListener(this);
  }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        img.setBackgroundResource(b?R.drawable.on:R.drawable.off);
//CompoundButton compoundButton代表被点击的控件本身
//b代表被点击控件的状态
//b?R.drawable.on:R.drawable.off--代表如果b开则显示on图片否则显示off图片

    }
}

ImageView里面改成了android:background=""属性,
所以后面对应的代码是setBackgroundResource;
如果把ImageView直接拖进来的时候选择图片是android:src="",
后面的代码就是setImageResource了

0人推荐
随时随地看视频
慕课网APP