首页 > 代码库 > android基础二之ToggleButton
android基础二之ToggleButton
//activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.vincentlin.togglebutton.MainActivity" > <!-- textOn:true textOff:false --> <ToggleButton android:id="@+id/toggleButton1" android:checked="false" android:textOn="@string/on" android:textOff="@string/off" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/off" /> </LinearLayout>
//strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ToggleButton</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="on">开</string> <string name="off">关</string> </resources>
MainActivity.java
package com.vincentlin.togglebutton; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ToggleButton; public class MainActivity extends Activity implements OnCheckedChangeListener{ private ToggleButton tButton; private ImageView iView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化组件 tButton = (ToggleButton) findViewById(R.id.toggleButton1); iView = (ImageView) findViewById(R.id.imageView1); /* * 给当前的tButton设置监听器 */ tButton.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { /* * * 当tButton被点击的时候,当前的方法会执行 * buttonView---代表被点击控件的本身, * isChecked---代表被点击的控件的状态 * 当点击这个tButton的时候,更换img的背景 */ iView.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off); } }
//效果图
android基础二之ToggleButton
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。