ToggleButton:有两种状态的Button(选中和未选中),可显示为不同的文本或者状态
属性:
android:checked=”ture”
按钮是否被选中
android:textOff=“关”
android:textOn=“开”
则ture显示的是开
功能实现:使用ToggleButton,来切换图片
layout
<ToggleButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ToggleButton"
android:id="@+id/toggleButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textOff="灯灭了"
android:textOn="灯亮了"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@id/image"
android:layout_below="@+id/toggleButton"
android:layout_centerHorizontal="true"
android:src="@drawable/lightoff"/>
MainActivity
public class MainActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton tbutton;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tbutton = (ToggleButton) findViewById(R.id.toggleButton);
image = (ImageView) findViewById(R.id.image);
// 为当前按钮设置点击监听
tbutton.setOnCheckedChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*
当button点击时,该方法会执行
buttonView----代表被点击的控件本身
isChecked--代表被点击控件的状态
当点击这个tbutton的时候,更换图片
*/
image.setImageResource(isChecked?R.drawable.lighton:R.drawable.lightoff);
}
}
界面实现,默认checked=flase,显示的是lightoff图片,文字是显示为灯灭了,点击后checked=true,显示的是lighton图片,文字是显示为灯亮了,可以来回多次切换