Android:带有文本和自定义视图的开关
创始人
2024-10-13 10:31:14
0

下面是一个带有文本和自定义视图的Android开关的代码示例:

  1. 创建一个自定义的SwitchButton类,继承自Switch类:
public class SwitchButton extends Switch {

    private TextView textView;

    public SwitchButton(Context context) {
        super(context);
        init(context);
    }

    public SwitchButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SwitchButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        // 添加文本视图
        textView = new TextView(context);
        textView.setTextOff("OFF");
        textView.setTextOn("ON");
        textView.setTextColor(Color.BLACK);
        textView.setGravity(Gravity.CENTER);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        addView(textView, layoutParams);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        // 设置文本视图的位置
        int centerX = (right - left) / 2;
        int centerY = (bottom - top) / 2;
        int textWidth = textView.getMeasuredWidth();
        int textHeight = textView.getMeasuredHeight();
        textView.layout(centerX - textWidth / 2, centerY - textHeight / 2, centerX + textWidth / 2, centerY + textHeight / 2);
    }
}
  1. 在布局文件中使用自定义的SwitchButton:

  1. 在Activity或Fragment中使用SwitchButton:
SwitchButton switchButton = findViewById(R.id.switchButton);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 处理开关状态变化事件
    }
});

这样就可以创建一个带有文本和自定义视图的开关控件了。

相关内容

热门资讯

一秒答解!wepoker辅助器... 一秒答解!wepoker辅助器如何使用,hhpoker有后台操控吗,教你教程(有挂辅助)是一款可以让...
今日头条!wepoker怎么挂... 今日头条!wepoker怎么挂飞机,竞技联盟辅助,普及教程(有挂技巧);亲真的是有正版授权,小编(透...
玩家必备科普!wejoker内... 玩家必备科普!wejoker内置辅助,wepoker透视最简单三个步骤,攻略教程(有挂教程);支持2...
总算了解!德扑圈透视,德普之星... 总算了解!德扑圈透视,德普之星透视辅助软件激活码,揭秘教程(有挂攻略);支持2-10人实时对战,虚拟...
盘点几款!德州圈脚本,hhpo... 盘点几款!德州圈脚本,hhpoker德州机器人,详细教程(有挂透明)关于hhpoker德州机器人机制...
今日焦点!hhpoker有没有... 今日焦点!hhpoker有没有作弊挂,pokerworld破解版下载,玩家教你(有挂方法)是由北京得...
揭秘!wpk透视插件,德普之星... 揭秘!wpk透视插件,德普之星透视辅助,2025新版技巧(有挂透明);玩家必备必赢加哟《136704...
玩家必备攻略!hhpoker辅... 玩家必备攻略!hhpoker辅助器视频,wpk插件辅助,wepoke教程(有挂攻略)科技教程也叫必备...
玩家实测!aapoker ai... 玩家实测!aapoker ai插件,poker红龙辅助,专业教程(有挂教程);最新版2024是一款经...
玩家必看教程!wepoker软... 1、玩家必看教程!wepoker软件安装包,epoker免费透视脚本,解密教程(有挂神器)2、进入游...