开发者

Android - using int value 0 as "null"-equivalent for R.drawable

开发者 https://www.devze.com 2023-02-14 03:58 出处:网络
I\'m using an intuitive but perhaps unorthodox shortcut, and I quite simply want to know if it may cause problems, is bad form, or if there is a different, more accepted way of doing it.

I'm using an intuitive but perhaps unorthodox shortcut, and I quite simply want to know if it may cause problems, is bad form, or if there is a different, more accepted way of doing it.

The shortcut is: in a function which expects an int which is an R.drawable constant, I sometimes use a 0 to act as an equivalent to passing "null".

Here's a sort of template of how I use this:

int someDrawable = isSomeCondition() ? R.drawable.somedrawable_identifier : 0; mHandler.post(new UpdateSomeUI(someDrawable));

//and, elsewhere in the application,
private class UpdateSomeUI implements Runnable {
    private final int someDrawable;

    public UpdateSomeUI(int someDrawable) {
        this.someDrawable = someDrawable;
    }

    public void run() {
        mSomeImageView.setImageResource(someDrawable);
    }
}

It seems to work - that is, so far it's been doing what I want, and so far I have observed no adverse effects like crashes or the creation of quantum singularities within the device.

Is 开发者_高级运维this safe to do? Is this bad form? I S'dTFW for some official integer value that would be recognized as "null" in this sort of circumstance, but came up empty. Does anyone know if such a value exists?

Edit: I realize that the tag "r" isn't referring to the one I want. The tag "android.R" doesn't seem to exist, however. I guess I'll remove the tag for now.


Found this on android documentation for Resource ID, sub-section constants, hope it helps.

Resource ID > Constants

Constants ID_NULL Added in API level 29 static val ID_NULL: Int The null resource ID. This denotes an invalid resource ID that is returned by the system when a resource is not found or the value is set to @null in XML.

Value: 0


There is no resource that represents "null" and by passing in an invalid resource id, an exception does get thrown and handled internally (when getDrawable(0) is called). The proper thing to do is to only call UpdateSomeUI(someDrawable) when there is actually a valid drawable.

Something like

//in a method somewhere: 
if(isSomeCondition()) {
    mHandler.post(new UpdateSomeUI(R.drawable.somedrawable_identifier));
}

What's wrong with doing it that way?

0

精彩评论

暂无评论...
验证码 换一张
取 消