Android 切换按钮、开关示例

今天我们将学习Android应用程序中的切换按钮和开关。我们将讨论并实现开关按钮控件和应用程序中的ToggleButton控件。

Android切换按钮

Android切换按钮用于显示按钮的开启和关闭状态。Switch 是从Android 4.0开始主要使用的另一种切换按钮。Android Switch提供了一个滑块控件。ToggleButton和Switch都是CompoundButton类的子类。用于定义ToggleButton的XML属性如下所述。

  1. android:disabledAlpha:禁用时应用于指标的alpha
  2. android:textOff:未选中时按钮的文本
  3. android:textOn:选中按钮时的文本

要以编程方式修改ToggleButton,请使用以下方法。

CharSequence getTextOff():按钮未处于选中状态时返回文本 CharSequence getTextOn():返回按钮处于选中状态时的文本 void setChecked(Boolean Checked):改变该按钮的选中状态

安卓交换机♪

Android Switch或 SwitchCompat 小部件(AppCompat库的一部分,为Android API v7之前的较低Android版本提供向后兼容性)是一个自定义的开关滑块,常见于手机设置中。** Android Switch Widget的优势** :

1.它是复选框和单选按钮的最佳替代品 2.实施只需不到一分钟 3.不需要使用太多的抽屉和其他资源

SwitchCompat的XML布局如下所示:

1<android.support.v7.widget.SwitchCompat
2        android:id="@+id/switchButton"
3        android:layout_width="wrap_content"
4        android:layout_height="wrap_content"
5        android:textAppearance="?android:attr/textAppearanceMedium"
6        android:text="Switch example"
7        />

android:ext用于在滑块开关按钮旁边显示文本。

Android切换按钮和切换示例

在此应用程序中,我们将显示两个ToggleButton和一个Switch按钮。当按下FloatingActionButton时,切换按钮的状态将显示在快捷栏中。每当单击快捷栏的操作按钮时,切换按钮的状态都会更改为True。或者通过滑动开关在快餐栏中显示状态。

Android Toggle Button和Switch项目结构

Android切换按钮,在Android中切换

Android切换按钮代码

active_main.xml保持不变。content_main.xml包含两个切换按钮和一个默认选中为False的开关,如下面的代码片断所示:

 1<?xml version="1.0" encoding="utf-8"?>
 2<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
 3    xmlns:app="https://schemas.android.com/apk/res-auto"
 4    xmlns:tools="https://schemas.android.com/tools"
 5    android:layout_width="match_parent"
 6    android:layout_height="match_parent"
 7    android:paddingBottom="@dimen/activity_vertical_margin"
 8    android:paddingLeft="@dimen/activity_horizontal_margin"
 9    android:paddingRight="@dimen/activity_horizontal_margin"
10    android:paddingTop="@dimen/activity_vertical_margin"
11    app:layout_behavior="@string/appbar_scrolling_view_behavior"
12    tools:context="com.journaldev.switchandtoggle.MainActivity"
13    tools:showIn="@layout/activity_main">
14
15    <ToggleButton
16        android:id="@+id/tb1"
17        android:layout_width="wrap_content"
18        android:layout_height="wrap_content"
19        android:layout_alignParentLeft="true"
20        android:layout_alignParentTop="true"
21        android:text="ToggleButton 1"
22        android:textOff="Off"
23        android:textOn="On" />
24
25    <ToggleButton
26        android:id="@+id/tb2"
27        android:layout_width="wrap_content"
28        android:layout_height="wrap_content"
29        android:layout_alignBaseline="@+id/tb1"
30        android:layout_alignBottom="@+id/tb1"
31        android:layout_toRightOf="@+id/tb1"
32        android:text="ToggleButton 2"
33        android:textOff="Off"
34        android:textOn="On" />
35
36    <android.support.v7.widget.SwitchCompat
37        android:id="@+id/switchButton"
38        android:layout_width="wrap_content"
39        android:layout_centerInParent="true"
40        android:checked="false"
41        android:layout_height="wrap_content"
42        android:textAppearance="?android:attr/textAppearanceMedium"
43        android:text="Switch example"
44        />
45
46</RelativeLayout>

MainActivity.java如下所示:

 1package com.journaldev.switchandtoggle;
 2
 3import android.graphics.Color;
 4import android.os.Bundle;
 5import android.support.design.widget.FloatingActionButton;
 6import android.support.design.widget.Snackbar;
 7import android.support.v7.app.AppCompatActivity;
 8import android.support.v7.widget.SwitchCompat;
 9import android.support.v7.widget.Toolbar;
10import android.view.View;
11import android.view.Menu;
12import android.view.MenuItem;
13import android.widget.CompoundButton;
14import android.widget.ToggleButton;
15
16public class MainActivity extends AppCompatActivity {
17
18    ToggleButton tb1, tb2;
19    SwitchCompat switchCompat;
20
21    @Override
22    protected void onCreate(Bundle savedInstanceState) {
23        super.onCreate(savedInstanceState);
24        setContentView(R.layout.activity_main);
25        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
26        setSupportActionBar(toolbar);
27
28        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
29        fab.setOnClickListener(new View.OnClickListener() {
30            @Override
31            public void onClick(View view) {
32
33                StringBuilder result = new StringBuilder();
34                result.append("ToggleButton1 : ").append(tb1.getText());
35                result.append("\nToggleButton2 : ").append(tb2.getText());
36
37               Snackbar snackbar= Snackbar.make(view, result.toString(), Snackbar.LENGTH_LONG)
38                        .setAction("SWITCH ENABLE", new View.OnClickListener() {
39                            @Override
40                            public void onClick(View v) {
41                                switchCompat.setChecked(true);
42                            }
43                        });
44
45                snackbar.setActionTextColor(Color.RED);
46                snackbar.show();
47            }
48        });
49
50        tb1= (ToggleButton)findViewById(R.id.tb1);
51        tb2=(ToggleButton)findViewById(R.id.tb2);
52        switchCompat=(SwitchCompat)findViewById(R.id.switchButton);
53
54        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
55            @Override
56            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
57
58                Snackbar.make(buttonView, "Switch state checked "+isChecked, Snackbar.LENGTH_LONG)
59                        .setAction("ACTION",null).show();
60            }
61        });
62
63    }
64
65    @Override
66    public boolean onCreateOptionsMenu(Menu menu) {
67        // Inflate the menu; this adds items to the action bar if it is present.
68        getMenuInflater().inflate(R.menu.menu_main, menu);
69        return true;
70    }
71
72    @Override
73    public boolean onOptionsItemSelected(MenuItem item) {
74        // Handle action bar item clicks here. The action bar will
75        // automatically handle clicks on the Home/Up button, so long
76        // as you specify a parent activity in AndroidManifest.xml.
77        int id = item.getItemId();
78
79        //noinspection SimplifiableIfStatement
80        if (id == R.id.action_settings) {
81            return true;
82        }
83
84        return super.onOptionsItemSelected(item);
85    }
86}

字符串构建器用于获取切换按钮的当前状态,并将其附加到snackbar.中显示Switch Button是复合按钮的子类,实现了OnCheckChangeListener,如上面的代码所示。下面的输出是运行中的应用程序。安卓切换按钮示例,切换到android这将结束安卓切换按钮并切换到安卓教程。你可以从下面的链接下载最终的Android SwitchAndTogle项目。

下载Android开关和切换按钮项目

参考:切换按钮安卓Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus