ToggleButton按钮

ToggleButton:有两种状态,选中和未选中状态,并且需要为不同的状态设置不同的显示文本。

属性:android:checked="true"    //为true时显示textOn的文本内容,false时显示为textOn的文本内容。

    android:textOff="关"

    android:textOn="开"

一个开关灯泡代码的实现:

MainActivity.java

package com.example.xuhai.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{

    private ToggleButton tb;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        tb=(ToggleButton)findViewById(R.id.tg1);
        img=(ImageView)findViewById(R.id.img1);
        tb.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //buttonView----代表被点击控件的本身
        //isChecked----代表被点击控件的状态
        img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);

    }
}

test.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView" />

    <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="小测试"
    />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="开关灯泡"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        >
        <ToggleButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tg1"
            android:textOn="开"
            android:textOff="关"
            />
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/off"
            android:id="@+id/img1"
            />
    </LinearLayout>
</LinearLayout>

显示结果:


总结:继承OnCheckedChangeListener接口,实现onCheckedChangedd方法,调用三目运算符来实现灯泡的开关状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值