Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

android - Compatibility of getContext and getResource between 5.0 and lower

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())}}  }); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...