Android 视图背景意外更改 [英] Android View background changes unexpectedly

查看:17
本文介绍了Android 视图背景意外更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个具有大量屏幕的应用.大多数屏幕的顶部都有一个带有背景颜色的视图.

I'm building an app that has plenty of screens. most of the screens have a View at the top with a background color.

我经常使用 view.setBackgroundColor(color) 改变颜色

I often change that color using view.setBackgroundColor(color)

奇怪的事情来了:有时在设置一个视图的颜色后,比如 #f14fb7 ,在应用程序中导航时,其他视图的背景被设置为该颜色,而我不希望它们如此.有时甚至会发生在我没有为其设置 id 的视图中,因此无法在这些视图上调用 setBackgroundColor.

Here comes the weird thing: sometimes after setting the color of one view, say to #f14fb7 , when navigating in the app, other views' backgrounds are set to that color without me wanting them to. It sometimes even happens to views I had not set an id for, so there is no way setBackgroundColor was called on those views.

这种情况很少发生,并且与我尝试过的任何流程都不一致.

This happens rarely and is not consistant to any flow I tried.

当我终止应用程序并重新启动它时,一切正常.

When I kill the app and restart it, everything works as it should.

我唯一的猜测是内存泄漏之王,但我希望有一个更简单的解释.

My only guess is some king of memory leak, but I hope there is a simpler explanation.

有人能想出发生这种情况的原因吗?

Can anyone think of some reason for this to happen?

*它发生在我的 Galaxy S3 上.

*It happens on my Galaxy S3.

推荐答案

没有代码,这并不容易...但我猜你是在多个视图上重用相同的 ColorDrawableView.setBackgroundColor()源码:

Without the code it's not easy... but I guess you are reusing the same ColorDrawable on multiple views and if you take a look at View.setBackgroundColor() source code :

public void setBackgroundColor(int color) {
    if (mBGDrawable instanceof ColorDrawable) {
        ((ColorDrawable) mBGDrawable).setColor(color);
    } else {
        setBackgroundDrawable(new ColorDrawable(color));
    }
}

你可以看到它改变了 ColorDrawable 的颜色并且每次都不会创建一个新的.我很确定这就是你有这种奇怪行为的原因.

You can see that it change the color of the ColorDrawable and don't create a new one each time. I'm pretty sure this is why you have this strange behavior.

编辑

当您使用 android:background 在 xml 中设置初始背景颜色时,您正在执行此操作(根据 android 文档):

When you set the initial background color in xml with android:background you are doing this (according android doc):

为给定资源设置背景.资源应该引用一个 Drawable 对象

Set the background to a given resource. The resource should refer to a Drawable object

根据我的理解,它会在膨胀期间设置字段 View.mBGDrawable.我建议你使用 View.setBackgoundDrawable(new ColorDrawable(the_color_int_code))) 而不是 setBackgroung(the_color_int_code).它应该可以解决您的问题.

According my understanding it will set the field View.mBGDrawable during the inflate. I suggest you to use View.setBackgoundDrawable(new ColorDrawable(the_color_int_code))) instead of setBackgroung(the_color_int_code). It should solve your issue.

这篇关于Android 视图背景意外更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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