MainActivity如下:
package cn.testimage; import android.os.Bundle; import android.widget.Button; import android.app.Activity; import android.graphics.drawable.Drawable.ConstantState; /** * Demo描述: * 依据Drawable的ConstantState判断两张图片是否是drawable中同一张图片 * */ public class MainActivity extends Activity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mButton=(Button) findViewById(R.id.button); ConstantState buttonConstantState= mButton.getBackground().getConstantState(); ConstantState resourceConstantState= getResources().getDrawable(R.drawable.ic_launcher).getConstantState(); boolean isEqual=buttonConstantState.equals(resourceConstantState); System.out.println("isEqual="+isEqual); } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/ic_launcher" android:layout_centerInParent="true" /> </RelativeLayout>