Android学习03
ToggleButton和Switch
状态开关ToggleButton与开关switch也是由button按钮派生出来的,因此他们的本质也是按钮,button支持的各种属性,方法toggleButton和switch也适用。
ToggleButton常用的属性:
android:textOff:按钮关闭时显示的文本;
android:textOn:按钮开启时显示的文本;
Switch也用于开关按钮。Switch和ToggleButton稍有区别:ToggleButton是按下弹起的开关,而Switch是左右滑动的开关。
开关监听为:setOnCheckedChangeListener,覆写onCheckedChanged(CompoundButton buttonView, boolean isChecked)方法,其中isChecked表示是否选中。
layout文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ToggleButton android:id="@+id/tbtn_open" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="开" android:textOff="关" android:checked="true"/> <Switch android:id="@+id/sw" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tbtn_open" android:layout_marginTop="20dp" android:checked="true"/> </RelativeLayout>
Activity
public class ToggleButtonActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{ private ToggleButton mBtnopen; private Switch mBtnsw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_toggle_button); mBtnopen = findViewById(R.id.tbtn_open); mBtnsw = findViewById(R.id.sw); mBtnopen.setOnCheckedChangeListener(this); mBtnsw.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { switch (compoundButton.getId()){ case R.id.tbtn_open: if(compoundButton.isChecked()) Toast.makeText(this,"开",Toast.LENGTH_SHORT).show(); else Toast.makeText(this,"关",Toast.LENGTH_SHORT).show(); break; case R.id.sw: if(compoundButton.isChecked()) Toast.makeText(this,"开关:ON",Toast.LENGTH_SHORT).show(); else Toast.makeText(this,"开关:OFF",Toast.LENGTH_SHORT).show(); break; } } }
效果图
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28