android.widget.Switch - 开/关事件监听器?

Joh*_*han 209 android

我想实现一个开关按钮,android.widget.Switch(可从API v.14获得).

<Switch
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Switch" />
Run Code Online (Sandbox Code Playgroud)

但我不知道如何为按钮添加事件监听器.它应该是一个"onClick"监听器吗?我怎么知道它是否"开启"了?

Sam*_*Sam 453

Switch继承了CompoundButton属性,所以我推荐使用OnCheckedChangeListener

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do something, the isChecked will be
        // true if the switch is in the On position
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 按钮有`OnCLick`,开关没有`OnChange`!精心设计的谷歌团队! (3认同)
  • @Johan没问题.我不知道你,但我希望他们将它命名为OnCheckChangedListener,类似于OnItemSelectedListener,因为On-_Noun _-_ Verb_-Listener是一个既定的命名对话. (2认同)
  • 但是,例如,当您将 放在片段上时,如果您将开关设置为 On,则每当您重新访问片段时,该东西总是会触发。 (2认同)
  • @KZoNE我在这里所做的是使用点击侦听器来更改状态并将切换传递给方法(在我的情况下是API调用)然后使用setChecked()方法来更改状态(例如API调用中的onFailure/onError) 。希望有帮助。 (2认同)

shr*_*ari 50

使用以下代码段通过XML将切换添加到布局:

<Switch
     android:id="@+id/on_off_switch"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textOff="OFF"
     android:textOn="ON"/>
Run Code Online (Sandbox Code Playgroud)

然后在Activity的onCreate方法中,获取对Switch的引用并设置其OnCheckedChangeListener:

Switch onOffSwitch = (Switch)  findViewById(R.id.on_off_switch); 
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Log.v("Switch State=", ""+isChecked);
}       

});
Run Code Online (Sandbox Code Playgroud)

  • 这是一个更清晰的答案,为您提供匹配的布局和代码. (3认同)

nef*_*tou 18

定义XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neoecosystem.samplex.SwitchActivity">

    <Switch
        android:id="@+id/myswitch"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</RelativeLayout> 
Run Code Online (Sandbox Code Playgroud)

然后创建一个Activity

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {

    Switch mySwitch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);


        mySwitch = (Switch) findViewById(R.id.myswitch);
        mySwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // do something when check is selected
        } else {
            //do something when unchecked
        }
    }

    ****
}
Run Code Online (Sandbox Code Playgroud)

========对于以下API 14,请使用SwitchCompat =========

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neoecosystem.samplex.SwitchActivity">

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/myswitch"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

活动

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {

    SwitchCompat mySwitch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);


        mySwitch = (SwitchCompat) findViewById(R.id.myswitch);
        mySwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // do something when checked is selected
        } else {
            //do something when unchecked
        }
    }
   *****
}
Run Code Online (Sandbox Code Playgroud)

  • 别忘了检查buttonView.isPressed() (2认同)

Fah*_*mad 15

对于使用Kotlin的用户,可以为交换机设置监听器(在这种情况下具有ID mySwitch),如下所示:

    mySwitch.setOnCheckedChangeListener { _, isChecked ->
         // do whatever you need to do when the switch is toggled here
    }
Run Code Online (Sandbox Code Playgroud)

isChecked 如果当前检查(ON)开关,则为true,否则为false.


Sha*_*ros 8

在科特林中:

        switch_button.setOnCheckedChangeListener { buttonView, isChecked ->
        if (isChecked) {
            // The switch enabled
            text_view.text = "Switch on"

        } else {
            // The switch disabled
            text_view.text = "Switch off"

        }
    }
Run Code Online (Sandbox Code Playgroud)


Abi*_*h R 5

Switch小部件的布局是这样的.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:gravity="right"
        android:text="All"
        android:textStyle="bold"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:id="@+id/list_toggle" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在Activity类中,您可以通过两种方式进行编码.取决于您可以编码的使用.

第一道路

public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.return_vehicle);

    list_toggle=(Switch)findViewById(R.id.list_toggle);
    list_toggle.setOnCheckedChangeListener(this);
    }
}

public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
    if(isChecked) {
        list_toggle.setText("Only Today's");  //To change the text near to switch
        Log.d("You are :", "Checked");
    }
    else {
        list_toggle.setText("All List");   //To change the text near to switch
        Log.d("You are :", " Not Checked");
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方式

public class ActivityClass extends Activity {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.return_vehicle);

    list_toggle=(Switch)findViewById(R.id.list_toggle);
    list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          if(isChecked) {
             list_toggle.setText("Only Today's");  //To change the text near to switch
             Log.d("You are :", "Checked");
          }
          else {
             list_toggle.setText("All List");  //To change the text near to switch
             Log.d("You are :", " Not Checked");
          }
       }       
     });
   }
}
Run Code Online (Sandbox Code Playgroud)


can*_*ler 5

2020 年 9 月 - 以编程方式回答

您可以通过编程方式为 Switch Widget 和 Material Design 完成此操作:

Switch yourSwitchButton = findViewById(R.id.switch_id);

yourSwitchButton.setChecked(true); // true is open, false is close.

yourSwitchButton.setOnCheckedChangeListener((compoundButton, b) -> {
        if (b){
          //open job.
        }  
        else  {
          //close job.
        }
    });
Run Code Online (Sandbox Code Playgroud)