Android学习之ToggleButton的使用

public class MainActivity extends ActionBarActivity implements
OnCheckedChangeListener {


private ToggleButton toggleButton;
private ImageView imageView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
imageView = (ImageView) findViewById(R.id.imageView1);
// 给toggleButton添加点击监听
toggleButton.setOnCheckedChangeListener(this);


}
/*
* toggleButton被点击时,调用该方法
*/
@Override

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

// toggleButton开启时,设置imageView图片为灯泡亮的图片,否则图片设置为灯泡不亮时的图片
imageView.setBackgroundResource(isChecked ? R.drawable.on
: R.drawable.off);


}


}

你可能感兴趣的:(Android学习)