使用ToggleButton实现图片更换

1:添加两个灯泡的图片在drawable中,取名为off/on


 

2:xml文件:

<ToggleButton
android:id="@+id/tbtn"
android:textOn="开"
android:textOff="关"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/off"/>


 

3:java文件:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//初始化控件:
setContentView(R.layout.activity_main);
tbtn=(ToggleButton) findViewById(R.id.tbtn);
img=(ImageView) findViewById(R.id.img);
//设置监听器:
tbtn.setOnCheckedChangeListener( this);

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
//当btnt点击时,当前方法会执行,buttonView:代表被点击的控件的本身 ,isChecked代表点击控件的状态 ,当点击按钮时,更换img背景
img.setBackgroundResource(isChecked?R.drawable.on,R.drawable.off);//如果点击了,则更换图片,三目运算符
}


 

posted @ 2016-04-11 12:49  icessun  阅读(1989)  评论(0编辑  收藏  举报