📜  Android ToggleButton示例

📅  最后修改于: 2020-09-29 02:07:33             🧑  作者: Mango

Android ToggleButton示例

Android切换按钮可用于在按钮上显示选中/未选中(打开/关闭)状态。

如果用户必须在两个状态之间更改设置,则将非常有益。它可以用于打开/关闭声音,Wifi,蓝牙等。

自Android 4.0以来,还有另一种类型的切换按钮(称为switch)提供了滑块控件。

Android ToggleButton和Switch都是CompoundButton类的子类。

Android ToggleButton类

ToggleButton类提供了创建切换按钮的便利。

ToggleButton类的XML属性

ToggleButton类的3个XML属性。

XML AttributeDescriptionandroid:disabledAlphaThe alpha to apply to the indicator when disabled.android:textOffThe text for the button when it is not checked.android:textOnThe text for the button when it is checked.

ToggleButton类的方法

下面给出了ToggleButton类的广泛使用的方法。

MethodDescriptionCharSequence getTextOff()Returns the text when button is not in the checked state.CharSequence getTextOn()Returns the text for when button is in the checked state.void setChecked(boolean checked)Changes the checked state of this button.

Android ToggleButton示例

activity_main.xml

拖动两个切换按钮和一个按钮进行布局。现在,activity_main.xml文件将如下所示:




    

    

    

活动课

让我们编写代码以检查哪个切换按钮处于ON / OFF状态。

package example.javatpoint.com.togglebutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    private ToggleButton toggleButton1, toggleButton2;
    private Button buttonSubmit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addListenerOnButtonClick();
    }

    public void addListenerOnButtonClick(){
        //Getting the ToggleButton and Button instance from the layout xml file
        toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
        toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
        buttonSubmit=(Button)findViewById(R.id.button);

        //Performing action on button click
        buttonSubmit.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                StringBuilder result = new StringBuilder();
                result.append("ToggleButton1 : ").append(toggleButton1.getText());
                result.append("\nToggleButton2 : ").append(toggleButton2.getText());
                //Displaying the message in toast
                Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show();
            }

        });

    }
}

输出: