解决此问题的最简单方法是创建一个工作线程,如线程和进程文档中所述。正如它所提到的,异步任务可用于将其替换为更复杂的代码。最终的解决方案是在方法中更改我的代码OnCreateView()
,替换原来的滞后代码:
final View rootView = inflater.inflate(R.layout.fragment_screen, container, false);
int i = getArguments().getInt(ARG_PANEL_NUMBER);
String panel = getResources().getStringArray(R.array.panel_array)[i];
int imageId = getResources().getIdentifier(panel.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.screen_image)).setImageDrawable(getResources().getDrawable(imageId));
使用新的后台线程:
final View rootView = inflater.inflate(R.layout.fragment_screen, container, false);
// Load image in a separate thread to ensure navigation drawer animation is smooth.
// Replace with Async Task if necessary
new Thread(new Runnable() {
public void run() {
int i = getArguments().getInt(ARG_PANEL_NUMBER);
final String panel = getResources().getStringArray(R.array.panel_array)[i];
int imageId = getResources().getIdentifier(panel.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
InputStream is = getActivity().getResources().openRawResource(imageId);
final Bitmap imageBitmap = BitmapFactory.decodeStream(is);
rootView.post( new Runnable() {
public void run() {
((ImageView) rootView.findViewById(R.id.screen_image)).setImageBitmap(imageBitmap);
getActivity().setTitle(panel);
}
});
}
}).start();
如上面文档中所述,如果此代码变得太大,则使用异步任务更具可扩展性和可维护性。