android基础二之ToggleButton

发布时间:2020-06-01 15:49:07 作者:小石头llx
来源:网络 阅读:325
//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/p_w_picpathView1"
        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.p_w_picpathView1);
  /*
   * 给当前的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

android基础二之ToggleButton

附件:http://down.51cto.com/data/2365305
推荐阅读:
  1. android基础之ListView
  2. android基础之CheckBox

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android togglebutton roi

上一篇:哈希如何帮助存储和检索HashMap中的值?

下一篇:MySQL多源复制配置实施步骤

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》