安卓——ToggleButton



1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.lenovo.testtogglebutton.MainActivity">

/*
    checked=true
    ToggleButton开始时显示textOn
    */
    <ToggleButton
        android:checked="false"
        android:textOn="开"
        android:textOff="关"
        android:id="@+id/toggleButton1"
        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/ic_launcher_foreground" />
</LinearLayout>

2.MainActivity

package com.example.lenovo.testtogglebutton;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener{
    private ToggleButton tb;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化条件
        img=(ImageView) findViewById(R.id.imageView1);
        tb=(ToggleButton) findViewById(R.id.toggleButton1);

        /*
        给当前的tb设置监听器
         */
        //写this的原因是MainActivity这个类实现了RadioGroup.OnCheckedChangeListener
        tb.setOnCheckedChangeListener(this);
    }


    //实现CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法
    @Override
    public void onCheckedChanged(CompoundButton Buttonview, boolean isChecked) {
        //当tb被点击的时候,当前的方法会执行
        /*
            Buttonview代表被点击控件的本身
            isChecked代表被点击的控件的状态

            当点击这个tb的时候,更换img的背景

         */
    //三目运算符:isChecked为true时是preview图片,为false是ic_launcher_foreground图片,这两张图片都在drawable文件夹下
        img.setBackgroundResource(isChecked?R.drawable.preview:R.drawable.ic_launcher_foreground);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水之积也不厚,则其负大舟也无力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值