1.新建一个layout,填写需要用到的控件:
light_control_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/light_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingLeft="20dp"
android:text=""
android:textSize="15sp"/>
<Switch
android:id="@+id/light_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingLeft="10dp"
android:text="开关:关"
android:textSize="15sp"/>
<TextView
android:id="@+id/brightstatus"
android:layout_width="80sp"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingLeft="10dp"
android:text="亮度:0"
android:textSize="15sp"/>
<SeekBar
android:id="@+id/brightness"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingLeft="10dp" />
</LinearLayout>
2.为此组合创建一个类:
LightSwitch.java
public class LightSwitch extends LinearLayout implements CompoundButton.OnCheckedChangeListener,SeekBar.OnSeekBarChangeListener {
private TextView lightNum;
private Switch lightSwitch;
private TextView brightStatus;
private SeekBar brightNess;
public LightSwitch(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
public LightSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public LightSwitch(Context context) {
super(context);
initView(context);
}
public void setName(String name){
lightNum.setText(name);
}
private void initView(Context context){
View.inflate(context, R.layout.light_control_layout, this);
lightNum = (TextView)findViewById(R.id.light_name);
lightSwitch = (Switch)findViewById(R.id.light_switch);
brightStatus = (TextView)findViewById(R.id.brightstatus);
brightNess = (SeekBar)findViewById(R.id.brightness);
lightSwitch.setOnCheckedChangeListener(this);
brightNess.setOnSeekBarChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()) {
Toast.makeText(getContext(),"打开灯光",Toast.LENGTH_SHORT).show();
lightSwitch.setText("开关:开");
}else {
Toast.makeText(getContext(),"关闭灯光",Toast.LENGTH_SHORT).show();
lightSwitch.setText("开关:关");
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
brightStatus.setText("亮度:"+progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getContext(), "修改亮度值", Toast.LENGTH_SHORT).show();
}
}
3.在Acitvity_main.layout中放置组合控件:
<com.rokkki.udp_6.LightSwitch
android:id="@+id/light_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
4.在MainActivity.java中就可以调用控件了。
lightContrl_1 = (LightSwitch)findViewById(R.id.light_1);