获取当前背景 [英] Get current background

查看:25
本文介绍了获取当前背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取当前背景以根据它做一个条件.例如,我有一个带有下一个箭头的xml,如果背景=R.drawable.A,我想在按下下一个按钮时将背景更改为R.drawable.B.

I want to get the current background to do a condition base on it. For example, I have a xml with a next arrow, if the background=R.drawable.A, I want to change the background to R.drawable.B when next Button is pressed.

我定义了我的相对布局如下:

I defined my relative layout as follows :

final RelativeLayout rl = (RelativeLayout) findViewById(R.id.myLayout);

if (rl.getBackground()== R.drawable.A){ //here the error
        rl.setBackgroundResource(R.drawable.B);
                }

错误是:不兼容的操作数类型 int 和 drawable.如果有办法获取当前背景并基于它做点什么?

The error is : incompatible operands types int and drawable. If there a way to get the current background and base on it do something?

推荐答案

其实我不知道他们为什么没有覆盖 Drawable 类.所以你应该使用 getConstantState() 方法来自返回 Drawable.ConstantState 的 Drawable 对象保存此 Drawable 的共享状态以便能够对其进行比较的实例.

Actually I don't know why they didn't override the equals method in the Drawable class. So you should use getConstantState() method from the Drawable object that returns a Drawable.ConstantState instance that holds the shared state of this Drawable to be able to compare it.

科特林

val drawableAConstantState = ContextCompat.getDrawable(this, R.drawable.A)?.constantState
rl.setBackgroundResource(if (rl.background?.constantState == drawableAConstantState) R.drawable.B else R.drawable.A)

Java

if (rl.getBackground() != null && rl.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.A).getConstantState()) {
    rl.setBackgroundResource(R.drawable.B);
} else {
    rl.setBackgroundResource(R.drawable.A);
}

这篇关于获取当前背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆