Compatibility of getContext and getResource betwee

2019-01-27 06:43发布

问题:

Hi so I released my app a few months ago and it all was working fine and to a degree it still does. On devices running lower than android 5 everything is fine. But I tested on a 5 device today and my if statements are not working. For example it marks every answer as incorrect yet on a lower device the correct incorrect answers is working as intended. I know my code works but I can't work out why it doesn't work on android 5. The only thing I can think of is that i've missed something out on my manifest.

EDIT: WORKING ANSWER allows compatibility between <=4.0 and 5.0=<:

 button.setOnClickListener(new OnClickListener(){

                    @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override
                    public void onClick(View arg0) {

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                            if (Word1.getDrawable().getConstantState().equals(Word1.getResources().getDrawable( R.drawable.img1).getConstantState())}}

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {        
                             if  (Word1.getDrawable().getConstantState().equals(Word1.getContext().getDrawable( R.drawable.img1).getConstantState())}}  }); 

回答1:

You need to use .equals to compare the objects.

== check if it's the same object not if the objects hold the same value, more info here

Your code shoud look like:

if(Word1.getDrawable().getConstantState().equals(getResources().getDrawable( R.drawable.img9).getConstantState())