ToggleButton控件两种状态,属性TextOn/TextOff,默认为未选中,android:checked="false",下面给出一个小例子:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ToggleButton
android:id="@+id/ToggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="关"
android:textOn="开" />
<ImageView
android:id="@+id/ImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/off" />
</LinearLayout>
下面事件绑定:实现OnCheckedChangeListener接口
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener{
private ToggleButton tg;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
tg = (ToggleButton) findViewById(R.id.ToggleButton1);
iv = (ImageView) findViewById(R.id.ImageView1);
//绑定事件
tg.setOnCheckedChangeListener(this);
}
//这里的参数 button为被操作的ToggleButton,isChecked为android:checked属性值
@Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
//设置背景图片
iv.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);//当checked为true是为on图片,false是off图片
}
}
效果图如下:
three.gif
网友评论