android:textOff="关"(默认状态)4>android:textOn="" />
android 开关按钮例子,Android自学笔记之ToggleButton(开关按钮)的功能、特殊属性、用法... |
您所在的位置:网站首页 › 开关图标素材 › android 开关按钮例子,Android自学笔记之ToggleButton(开关按钮)的功能、特殊属性、用法... |
1.ToggleButton属性: 1>有两种状态:选中和未选中状态并需要为不同的状态设置不同的显示文本 2>android:checked="true" 3>android:textOff="关"(默认状态) 4>android:textOn="开" 2.使用方法:(example) public class MainActivity extends Activity implements onCheckedChangeListener{ 1>初始化控件 2>给控件赋值 3>给控件设置监听器 4>重写onCheckedChanged()方法{ //当控件被点击时执行,isChecked代表被点击的控件的状态 imageView.setBackGroundResource(isChecked?R.drawable.on:R.drawable.off); } } 下面看一下具体代码的实现:为了大家观看方便我设置了两张图片,开的时候是一张图片,关的时候是两一张图片 首先是:activity_main.xml android:checked="false" android:textOn="开" android:textOff="关" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toggleButton" /> android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageView" android:layout_below="@+id/toggleButton" android:background="@drawable/on" /> 最后是:MainActivity.class package com.example.administrator.togglebutton1; import android.content.DialogInterface; import android.media.Image; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ToggleButton; public class MainActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener { private ToggleButton tb; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tb = (ToggleButton) findViewById(R.id.toggleButton); //初始化 img = (ImageView)findViewById(R.id.imageView); tb.setOnCheckedChangeListener(this); // 给控件设置监听器 } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //重写onCheckedChanged()方法 //当控件被点击时执行,isChecked代表被点击的控件的状态 img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.ic_adc); } } |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |