Android - Loading drawables without skipping frames

独自空忆成欢 提交于 2019-12-25 06:47:01

问题


Okay, so I am using a drawable PNG (1200 x 1920, 30kb) as a background in an activity. A snippet of my XML code is shown below. My problem is the application is skipping frames and has lagged responses. Could anybody tell me why this is happening, or a good way to solve my problem? I still would like to be able to use this PNG file as the background. Thanks

XML Snippet:

<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"
    android:background="@drawable/MY_PNG_BACKGROUND"
    tools:context=".MainActivity">

Logcat message:

I/Choreographer: Skipped 53 frames!  The application may be doing too much work on its main thread.

Things I have looked at:

  • Imageview skipped frames (This may work for me if someone can tell me how to do it in XML instead of programmatically in Java)
  • background images causing frames to be skipped

回答1:


Thanks to some help from CommonsWare in the comments, I was able to figure this out. I pre-loaded the drawable in my java class in the background using AsyncTask. Here is a code example:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Calling the task to be done in the background, in this case loading the drawable
        new LoadDrawable().execute();

    }

    private class LoadDrawable extends AsyncTask<Drawable, Void, Drawable> {
        @Override
        protected Drawable doInBackground(Drawable... params) {
            //Loading the drawable in the background
            final Drawable image = getResources().getDrawable(R.drawable.my_drawable);
            //After the drawable is loaded, onPostExecute is called
            return image;
        }

        @Override
        protected void onPostExecute(Drawable loaded) {
            //Hide the progress bar
            ProgressBar progress = (ProgressBar) findViewById(R.id.progress_bar);
            progress.setVisibility(View.GONE);
            //Set the layout background with your loaded drawable
            RelativeLayout layout = (RelativeLayout) findViewById(R.id.my_layout);
            layout.setBackgroundDrawable(loaded);
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}


来源:https://stackoverflow.com/questions/35107914/android-loading-drawables-without-skipping-frames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!