前面的内容以后有机会补充,现在从中级控件开始
-----------------------------------------------------------------------
视图部分:
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_weight="1"
android:layout_gravity="start"
android:text="switch开关:" />
<Switch
android:id="@+id/sw_status"
android:layout_width="80dp"
android:layout_height="30dp"
android:padding="5dp"
android:layout_gravity="end" />
</LinearLayout>
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="start" />
</LinearLayout>
对应Activity:
package com.example.chapter05;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class SwitchDefaultActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private TextView tv_result;
private Switch sw_status;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_default);
tv_result = findViewById(R.id.tv_result);
sw_status = findViewById(R.id.sw_status);
sw_status.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String desc = String.format("Switch开关的状态是:%s", b ? "open" : "close");
tv_result.setText(desc);
}
}
别忘了注册这个Act为主Act:
<activity
android:name=".SwitchDefaultActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
最后效果:
完成!