RadioGroup底部Tab的动态添加

Android典型界面设计——ViewPage+Fragment实现区域顶部tab滑动切换 一、问题描述   本系列将结合案例应用,陆续向大家介绍一些Android典型界面的设计,首先说说tab导航,导航分为一层和两层(底部区块+区域内头部导航),主要实现方案有RadioGroup+ViewPage+Fragment、Viewpager Indicator、ActionBar Tabs、FragmentTabHost+Fragment等,下面我们先采用RadioGroup+ 阅读详情

 

本文主要实现底部Tab的动态添加,动态添加图片、文字状态选择器,支持tab的本和和网络图片,支持各自Tab各自控制,支持Tab的隐藏和显示,非常灵活。实现原理是自定义RadioGroup+RadioButton,效果图如下:

关于小红点和角标实现参考上一篇文章介绍:

https://blog.csdn.net/yoonerloop/article/details/107589057

要实现单选效果RadioGroup包含的子View只能是RadioButton,不能为LinearLayout,为LinearLayout则单选效果和一系列的监听就失效了,要实现子View为LinearLayout的单选只能重写LinearLayout了,可以参考:https://www.cnblogs.com/over140/p/3795877.html,这里直接使用RadioButton实现。

一、xml定义

<?xml version="1.0" encoding="utf-8"?>
<com.tencent.weapps.view.AppRadioButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ab_btn"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:button="@null"
    android:singleLine="true"
    android:ellipsize="end"
    android:gravity="center"
    android:paddingTop="15dp"
    android:background="@android:color/transparent"
    android:textColor="@color/selector_tab_text"
    android:textSize="11sp" />

二、MyRadioGroup继承自RadioGroup动态添加

    private void initView() {
        if (list == null || list.isEmpty()) {
            setVisibility(GONE);
            return;
        }
        removeAllViews();
        setOrientation(HORIZONTAL);
        setVisibility(VISIBLE);
        //添加RadioButton
        for (int i = 0; i < list.size(); i++) {
            AppRadioButton radioButton = (AppRadioButton) LayoutInflater.from(getContext()).inflate(R.layout.item_tab, null);
            radioButton.setId(i);
            addView(radioButton);
        }
        //设置RadioButton属性
        for (int i = 0; i < getChildCount(); i++) {
            AppRadioButton radioButton = (AppRadioButton) getChildAt(i);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) radioButton.getLayoutParams();
            layoutParams.weight = 1;
            layoutParams.width = 0;
            layoutParams.gravity = Gravity.CENTER;
            radioButton.setLayoutParams(layoutParams);
            if (i == 0 && !radioButton.isChecked()) {
                radioButton.setChecked(true);
            } else {
                radioButton.setChecked(false);
            }
            if (!TextUtils.isEmpty(color) && !TextUtils.isEmpty(selectedColor)) {
                radioButton.setTextColor(getCheckedColorStateList(selectedColor, color));
            }
        }
        if (!TextUtils.isEmpty(backgroundColor)) {
            setBackgroundColor(Color.parseColor(backgroundColor));
        }
    }

    //设置背景颜色的状态选择器
    public static ColorStateList getCheckedColorStateList(@NonNull String checkedColor, 
        @NonNull String unCheckedColor) {
        int[][] states = new int[][]{
                new int[]{-android.R.attr.state_checked}, // unchecked
                new int[]{android.R.attr.state_checked}  // checked
        };
        int[] colors = new int[]{
                Color.parseColor(checkedColor),
                Color.parseColor(unCheckedColor)
        };
        return new ColorStateList(states, colors);
    }

注意这里不能偷懒,把添加RadioButton和设置属性放在一块去了,否则无法控制文字和icon之间的间距,绘制过程出现问题,要分开进行。

三、设置icon和文字

    private void setData() {
        if (list == null || list.isEmpty()) {
            setVisibility(GONE);
            return;
        }
        for (int i = 0; i < getChildCount(); i++) {
            TabBean bean = list.get(i);
            AppRadioButton radioButton = (AppRadioButton) getChildAt(i);
            setRadioButton(radioButton, bean);
        }
    }

    private void setRadioButton(AppRadioButton radioButton, TabBean bean) {
        ViewUtils.setText(radioButton, bean.text);
        if (TextUtils.isEmpty(bean.iconPath)) {
            radioButton.setTextSize(16);
            return;
        } else {
            radioButton.setTextSize(11);
        }
        radioButton.setCompoundDrawablePadding(drawablePadding);
        StateListDrawable stateListDrawable = new StateListDrawable();
        if (!bean.iconPath.startsWith("http") && !bean.selectedIconPath.startsWith("http")) {
            try {
                InputStream open = getResources().getAssets().open(bean.iconPath);
                InputStream selectOpen = getResources().getAssets().open(bean.selectedIconPath);
                Drawable drawable = Drawable.createFromStream(open, null);
                Drawable selectDrawable = Drawable.createFromStream(selectOpen, null);
                stateListDrawable.addState(new int[]{-android.R.attr.state_checked}, drawable);
                stateListDrawable.addState(new int[]{android.R.attr.state_checked}, selectDrawable);
                stateListDrawable.setBounds(0, 0, drawableSize, drawableSize);
                radioButton.setCompoundDrawables(null, stateListDrawable, null, null);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        Glide.with(getContext()).load(bean.iconPath).error(R.drawable.shape_circle_tab_default).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                if (resource == null) {
                    return;
                }
                stateListDrawable.addState(new int[]{-android.R.attr.state_checked}, resource);
                Glide.with(getContext()).load(bean.selectedIconPath).into(new SimpleTarget<Drawable>() {

                    @Override
                    public void onResourceReady(@NonNull Drawable selectResource, @Nullable Transition<? super Drawable> transition) {
                        if (selectResource == null) {
                            return;
                        }
                        stateListDrawable.addState(new int[]{android.R.attr.state_checked}, selectResource);
                        stateListDrawable.setBounds(0, 0, drawableSize, drawableSize);
                        radioButton.setCompoundDrawables(null, stateListDrawable, null, null);
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        resource.setBounds(0, 0, drawableSize, drawableSize);
                        radioButton.setCompoundDrawables(null, resource, null, null);
                    }
                });
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                Log.d("TAG",iconPath加载失败:"+ bean.selectedIconPath);
            }
        });
    }

四、更新RadioGroup属性

    public void upRadioButton(TabBean bean, int index) {
        if (getChildCount() == 0 || bean == null) {
            return;
        }
        for (int i = 0; i < getChildCount(); i++) {
            if (index == i) {
                AppRadioButton radioButton = (AppRadioButton) getChildAt(i);
                setRadioButton(radioButton, bean);
            }
        }
    }

五、更新右上角角标

    /**
     * 更新小红点
     * @param index
     * @param isShow
     */
    public void showRedPoint(int index, boolean isShow) {
        for (int i = 0; i < getChildCount(); i++) {
            if (index == i) {
                AppRadioButton radioButton = (AppRadioButton) getChildAt(i);
                radioButton.setShowSmallDot(isShow);
            }
        }
    }
    /**
     * 更新文字
     * @param index
     * @param text
     * @param isShow
     */
    public void showRedText(int index, String text, boolean isShow) {
        for (int i = 0; i < getChildCount(); i++) {
            if (index == i) {
                AppRadioButton radioButton = (AppRadioButton) getChildAt(i);
                radioButton.setNumberDot(isShow, text);
            }
        }
    }

 

 

深入理解Android Tab之radiogroup+fragment实现 Fragment代表应用程序用户界面中的一块功能区域。它拥有自己的布局和行为,可以看作是一个mini activity。Fragment的使用可以让应用界面更加模块化,易于管理。它不是直接运行在Activity上,而是必须嵌入到Activity中使用。Fragment可以存在于一个活动的用户界面中,并且可以从一个Activity中附加或分离。这意味着可以根据用户的交互来动态地修改屏幕上的内容。Android允许开发者对底部导航栏进行高度定制,包括图标、文字、背景以及选中状态的动画效果。 阅读详情

相关推荐

Android fragment制作微信菜单界面

用fragment做的一个仿微信菜单的demo,有兴趣的可以下载下来看着学习一下!

RadioGroup动态添加RadioButton,并且获得事件

由于有许多的RadioButton是动态的,不是固定的一些,所以需要在代码中,动态的添加到RadioGroup中,下面是我的实现方法。 1、添加RadioButton到RadioGroup中 [java]  view plain copy RadioGroup group;  for(int i=0; i10; i++)  {      Radio

当富网络 1537

RadioGroup实现APP首页底部Tab的切换

RadioGroup实现APP首页底部Tab的切换,原文链接:http://www.cnblogs.com/smyhvae/p/4463931.html

Android中RadioGroup在代码中动态添加子控件RadioButton

如下图: 我用红线圈出的地方,这个地方想来还得在代码中动态生成,因为个数你不确定 下面看代码: import java.util.ArrayList; import java.util.List; import com.ss.b.helps.DensityUtilHelps; import android.app.Activity; import android.graphics.C

麦壳的记忆 2万+

动态添加RadioGroup的RadioButton.rar

动态添加RadioGroup的RadioButton.rar

Android实现购物车及其他功能的角标

本文主要介绍了Android实现购物车及其他功能的角标的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧

RadioGroup中动态添加RadioButton

for (int i = 0; i < mDeliveryPayModeBeans.size(); i++) {//设置数量 RadioButton tempButton = new RadioButton(DeliveryDeliveredActivity.this);//this就是你的activity RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, View

qq_28641023的博客 585

android中radioGroup动态添加radioButton

android中radioGroup动态添加radioButton

RadioButton小红点、数字角标的实现

RadioButton通常作为RadioGroup的子布局嵌套在里面,单独使用不太常用,本文实现RadioButton小红点、数字角标,主要是利用onDraw方法进行重写,绘制小红点、数字角标。如下: public class AppRadioButton extends AppCompatRadioButton { private Paint mPaint; private boolean isShowDot; private boolean isShowNumbe..

一杯清泉 1935

基于Plecs的LLC谐振变换器闭环设计:从PI参数整定到动态响应优化

本文详细介绍了在Plecs仿真环境中,如何为半桥LLC谐振变换器设计并优化闭环控制系统。从开环模型搭建与特性分析入手,重点阐述了基于频域法的PI控制器参数整定流程,并通过负载阶跃、输入电压突变等测试优化动态响应。文章还分享了从仿真模型过渡到实际硬件时的关键注意事项,帮助工程师实现稳定、高效的电源设计。

e4f5g6h的博客 629

Halcon手眼标定实战:从九点标定到机械臂精准抓取(附完整代码)

本文详细介绍了Halcon手眼标定技术在实际工业场景中的应用,重点讲解了九点标定法在机械臂精准抓取中的实现步骤和优化技巧。通过对比Eye-to-Hand和Eye-in-Hand两种模式的特点,提供完整的代码示例和误差分析,帮助工程师快速掌握标定技术,提升自动化系统的精度和稳定性。

weixin_29100927的博客 466

Android新闻客户端(仿网易)--上

效果截图本来想找个软件动态截图,但是好像没找着。。。这样的话,看不出来点击之后的动态切换效果了。以后找着了再来替换。 [img]http://www.eoeandroid.com/data/attachment/forum/201212/25/135448umt5valrithrcvm9.png[/img][img]http://www.eoeandroid.com/data/attachm...

乐乐乖乖的博客 354

从0到1:.NET 9 OpenAPI全攻略!Swagger vs Scalar UI谁更强?

OpenAPI:.NET 9的智能文档革命 本文深入解析.NET 9的OpenAPI支持,对比Swagger UI与Scalar UI的优劣,提供实战代码示例: 一键生成:AddOpenApi()+MapOpenApi()快速生成标准文档 UI工具对决: Swagger UI功能全面但复杂 Scalar UI简约现代,原生支持cURL/HTTPie 进阶技巧: XML注释增强文档可读性 自定义Transformer实现文档动态修改 🔥核心价值:.NET 9的OpenAPI方案显著降低API文档维护成本,开

java专栏 1435

Tab效果之radiogroup+fragment

今天第一次写boge

bzy601638015的专栏 904

2023年全国职业院校技能大赛“信息安全管理与评估”-真题——赛题题目+答案解析

2023年全国职业院校技能大赛“信息安全管理与评估”-真题——赛题题目+答案解析

君逍遥o 6053

高通SA8295P音频接口深度解析:全面掌握SA8295P的LS-I2S、PCM/TDM与高性能音频处理技术设计

SA8295P提供丰富的音频接口选项,包括LS-I2S、PCM/TDM和HS-I2S接口,具备灵活的配置选项,适合各种高保真音频和高速数据传输应用。结合LS-I2S和PCM/TDM接口:在复杂的音频编解码器设计中,可结合使用LS-I2S和PCM/TDM接口,以处理和传输不同的音频数据流。使用HS-I2S接口:在软件定义无线电(SDR)系统中,高速I2S接口可处理高速数据流,如无线电信号的解码和处理。LS-I2S(低速I2S)接口是SA8295P的一部分,提供了丰富的音频数据传输选项。

weixin_43199439的博客 1416

Android 底部导航栏(底部Tab)最佳实践

本文目录.png 当开始一个新项目的时候,有一个很重要的步骤就是确定我们的APP首页框架,也就是用户从桌面点击APP 图标,进入APP 首页的时候展示给用户的框架,比如微信,展示了有四个Tab,分别对应不同的板块(微信、通讯录、发现、我),现在市面出了少部分的Material Design 风格的除外,大部分都是这样的一个框架,称之为底部导航栏,分为3-5个Tab不等。前段时间开始了一个

Be a valuable programmer 2万+

Claude Code 首次运行:交互式体验与基础命令

自然语言交互:直接用中文或英文描述需求斜杠命令:执行特定功能的快捷方式多轮对话:在上下文中逐步完善代码权限确认:理解并配置安全机制下一篇文章,我们将深入探讨 Claude Code 的核心工具,从文件操作开始,详细了解它是如何处理代码的。

gaoxiang_120的专栏 103

Android 动态切换底部tab按钮

身为一个Android开发人员,总是会遇到很多需求 直接上代码,代码里有注释,我使用的就是原生的radioGroup+radioButton public class IndexActivity extends AppCompatActivity { private RadioGroup index_rg_bottom; private RadioButton index_...

bigahua的博客 1433

【量化入门】Tushare库获取公募基金的历史净值

在本文中,我们将介绍如何使用Python的Tushare库获取公募基金的历史净值。

木头大左的博客 1151

Ollama + OpenCLAW 在 Windows 系统的完整部署指南

Windows 部署优先选 WSL2,避免原生环境的权限/兼容性问题;网络问题通过“离线包+国内镜像”解决,版本问题通过升级 Node.js 解决;内存不足可切换轻量模型或增大 WSL2 内存分配;核心链路:Ollama(模型管理)→ Gateway(网关)→ OpenCLAW TUI(交互),各组件启动正常即可稳定使用。

lpfasd123的博客 2839

Android 多点触控 RadioGroup + Fragment 实现的底部Tab 能防止用户同时点击多个button而只响应一个有效事件吗?

Android底部导航栏(底部Tab)是一个Android程序员入门必须会实现的一个功能点,在Material Design(基于Android 5.0 API level 21)设计出来之前大家实现底部Tab通常会用FragmentTabHost或RadioGroup方式。而在有了 Android Support Library (com.android.support:design:xx.x...

huch的博客 927

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Android底部tab导航栏中间凸起、动态配置替换底部导航栏Tab图标

Android底部tab导航栏中间凸起、动态配置替换底部导航栏Tab图标

weixin_38090079的博客 1571

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

安卓实现首页底部导航菜单中间图标凸起效果

效果图 1,Activity代码如下: public class ThirdActivity extends BaseActivity { @BindView(R.id.fl_layout) FrameLayout flLayout; @BindView(R.id.radioGroup) RadioGroup radioGroup; @BindView(...

智玲君 2906

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

通过RadioGroup组件实现微信底部的切换按钮(Tab》

<RadioGroup android:id="@+id/radiogroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" androi

ArchurSpace 590

底部导航栏点击跳转fragment

网上找了很多底部导航栏fragment切换,感觉各种方法都试了,下面是我自己整理的,希望能帮到大家。 (1)点击图片变色的xml文件写好。图片自己处理好。一个为例,其三个同理。 <selector xmlns:android="http://schemas.android.com/apk/res/android"> (2)layout布局文件的引用。

CSDNYUANDAIMAXUEXI的博客 2178
上一篇: RadioButton小红点、数字角标的实现
下一篇: CameraX实现预览、拍照、录制视频
一杯清泉
博客等级 码龄11年 314粉丝 210原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值