使用ToggleButton按钮实现的灯泡开关效果

xiaoxiao2021-02-28  9

示例图:

activity.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" tools:context="com.yongninggo.helloworld1.MainActivity" android:orientation="vertical"> <ToggleButton android:id="@+id/togbutton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:textOff="关" android:textOn="开"/> <ImageView android:id="@+id/image1" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/image1"/> </LinearLayout>

Activity.Java文件

package com.yongninggo.helloworld1; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ToggleButton; public class Activity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { private ToggleButton toggleButton; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity); toggleButton = (ToggleButton) findViewById(R.id.togbutton); imageView = (ImageView) findViewById(R.id.image1); toggleButton.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { toggleButton.setChecked(isChecked); imageView.setImageResource(isChecked ? R.drawable.image1 : R.drawable.image2); } }

转载请注明原文地址: https://www.6miu.com/read-1100310.html

最新回复(0)