切换同一个位置上的图片setCompoundDrawables

本文介绍了一种在不同界面中同一位置动态切换按钮图标的方法。通过判断当前界面类型,选择合适的图片资源并设置到按钮上,实现了保存、添加等操作的图标显示。特别注意的是,为了保持图标形状不被拉伸变形,需要正确设置图片的边界。

需求:
要在同一个位置上,如右上角,在不同的界面上,显示不同图片。
描述:
右上角,出现保存按钮(勾√)和添加按钮(+),在保存界面出现+,在提交界面出现√。
实现:

public void getRightChangeBtn(String str) {
        Drawable drawable;

        if (str.equals(RIGHT_SUBMIT)) {
            drawable = getResources().getDrawable(R.drawable.btn_true);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            fbSave.setCompoundDrawables(null, null, drawable, null);
        } else if (str.equals(RIGHT_ADD)) {
            drawable = getResources().getDrawable(R.drawable.btn_add);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            fbSave.setCompoundDrawables(null, null, drawable, null);
        } else if (str.equals(RIGHT_SAVE)) {
            drawable = getResources().getDrawable(R.drawable.btn_true);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            fbSave.setCompoundDrawables(null, null, drawable, null);
        }else if (str.equals(RIGHT_NULL)) {
            fbSave.setVisibility(View.INVISIBLE);
        }
        fbSave.setWidth(fbSave.getWidth());

        fbSave.setPadding(fbSave.getPaddingLeft(), fbSave.getPaddingTop(), fbSave.getPaddingRight(), fbSave.getPaddingBottom());
    }

特别注意,要设置边界

drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界

如果不设置边界,图片会变形。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值