当前位置: 首页 > news >正文

android studio开关控制

MainActivity.java代码:

package com.example.myapplication;import android.os.Bundle;
import android.util.Log;
import android.widget.Switch;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private Switch mySwitch;private TextView statusText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mySwitch = findViewById(R.id.my_switch);statusText = findViewById(R.id.status_text);// 设置监听器mySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {Log.d("SwitchLog", "buttonView: " + isChecked);switch (isChecked ? 1 : 0) {case 1:statusText.setText("当前状态:开启");break;case 0:statusText.setText("当前状态:关闭");break;}});}
}
activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:padding="24dp"><Switchandroid:id="@+id/my_switch"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开关控制" /><TextViewandroid:id="@+id/status_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="当前状态:关闭"android:layout_marginTop="16dp"android:textSize="18sp" />
</LinearLayout>

运行结果:

综上可得:

控件:

Switch

工具:android studio

软件:Windows11

Switch监听器:

setOnCheckedChangeListener

Log.d日志打印:

Log.d("SwitchLog", "buttonView: " + isChecked);mySwitch = findViewById(R.id.my_switch);
mySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {Log.d("SwitchLog", "buttonView: " + isChecked);switch (isChecked ? 1 : 0) {case 1:statusText.setText("当前状态:开启");break;case 0:statusText.setText("当前状态:关闭");break;}});

xml:

<Switchandroid:id="@+id/my_switch"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开关控制" />
java的tatusText.setText("当前状态:开启");可以更新xml的TextView控件的android:text内容

其中

tatusText即为statusText = findViewById(R.id.status_text);

相关文章:

  • 李沐 《动手学深度学习》 | 实战Kaggle比赛:预测房价
  • 离线部署openstack 2024.1 cinder
  • 深度解读谷歌Brain++液态神经网络:重塑动态智能的流体计算革命
  • DC1靶机渗透
  • 什么是JSON ?从核心语法到编辑器
  • 如何在docker desktop上安装mysql
  • 【清晰教程】可视化数据集标注工具Labelimg零基础安装
  • 系统集成自动化流程编排流实现 if-else 条件分支(一)
  • 以太网MDI信号PCB EMC设计要点
  • 禁止 Windows 更新后自动重启
  • 无人机避障——感知篇(在Ubuntu20.04的Orin nx上基于ZED2实现Vins Fusion)
  • 系统集成自动化流程编排实现条件分支高级篇(二)
  • 一般增长率
  • 大量RPM仓库管理指南:更新与批量获取实战手册
  • Manus AI与多语言手写识别技术突破
  • LangSmith 实战指南:大模型链路调试与监控的深度解析
  • DeepCritic: SFT+RL两阶段训练突破LLM自我监督!显著提升大模型的自我批判能力!!
  • 离线部署openstack 2024.1 placement
  • c++算法学习6——迪杰斯特拉算法
  • 彻底禁用Windows Defender通知和图标
  • php 个人网站 源码/优化设计七年级上册数学答案
  • 深圳专业企业网站建设/谷歌关键词推广怎么做
  • 中山城市建设集团网站/推广赚钱的平台有哪些
  • 长沙网站建设 个人/百度搜索量
  • 建设工程施工合同示范文本2021/网站关键词排名优化电话
  • 响应式网站建设费用/网络营销成功案例有哪些2022