Efficiency getDrawable (): Is Drawable a cached structure?

I need to change the image of the toggle button each time I press.

Is it effective to do this?

public void onClickToggleButton(View v) { if(_on) { _on=false; myImageView.setImageDrawable(getResources().getDrawable(R.drawable.btn_off)); } else { _on=true; myImageView.setImageDrawable(getResources().getDrawable(R.drawable.btn_on)); } } 

Or does this mean that Drawable will be decoded from a PNG file every time?

In this case, calling getDrawable() only twice (in onCreate() ) and saving my own links to 2 Drawable would be better.

+7
performance android android-drawable
source share
1 answer

This will not answer your question if it is effective or does not call this method each time. But, as @ njzk2 noted, you can use the State Selector on the toggle button.

I am copying you a working example (I use). Just change the drawable name with your drawings.

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/toggle_on" android:state_checked="true" /> <item android:drawable="@drawable/toggle_off" android:state_checked="false" /> </selector> 

On your xml, where you define your Google button, set the background as:

 android:background="@drawable/toogle_selector" 

Where "toogle_selector" is the name of the file I copied before.

With this, you can forget the download efficiency every time.

Hope this helps.

0
source share

All Articles