ビットマップを AsyncTask から ImageView にロードするときに、途切れが発生します。
SQLite から読み込まれた情報を表示するフラグメントがあり、その情報にはしばしば写真が添付されています。フラグメントが起動されると、表示されるまでに最大 1 秒かかります (アプリが少しハングしているように見えます)。これはおそらくデータの読み込みが重いためであり、何か間違ったことをしている可能性があります。
これが私の実装の簡素化されたバージョンです。
public class InformationFragment extends Fragment {
private ArrayList<MyPhoto> mPhotos;
private LinearLayout mPhotoContainer;
private View mView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ....
mView = inflater.inflate(R.layout.fragment_information, container, false);
mPhotoContainer = (LinearLayout) mView.findViewById(R.id.fragment_information_photos_container);
return mView;
}
@Override
public void onResume() {
super.onResume();
loadInformation();
}
private void loadInformation() {
// Loads information from database and puts it into TextViews and such.
// Relatively performance heavy operations, should perhaps run off main, but it's not the cause
// of my problems as it was pretty smooth before I implemented photo attachments
}
private ArrayList<MyPhoto> getPhotos() {
// Loads photos from database. Not sure but could be pretty performance heavy, you tell me :)
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(mPhotoContainer.getChildCount() == 0) {
mPhotos = getPhotos();
for (MyPhoto p : mPhotos) {
addImageViewForPhoto(p);
}
}
}
private void addImageViewForPhoto(MyPhoto p) {
final ImageView iv = new ImageView(getActivity());
mPhotoContainer.addView(iv);
new MyPhotoLoaderTask(iv).execute(p.getBytes());
}
}
以下は MyPhotoLoaderTask クラスです
public class MyPhotoLoaderTask extends AsyncTask<byte[], Void, Bitmap> {
private final WeakReference<ImageView> mWeakImageView;
public MyPhotoLoaderTask(ImageView iv) {
mWeakImageView = new WeakReference<ImageView>(iv);
}
@Override
protected Bitmap doInBackground(byte[]... params) {
return MyPhotoUtils.createBitmap(params[0], 100, 100);
}
@Override
protected void onPostExecute(final Bitmap result) {
if(mWeakImageView != null && result != null) {
final ImageView iv = mWeakImageView.get();
iv.setImageBitmap(result);
}
}
}
最後に MyPhotoUtils.createBitmap() メソッド
public static Bitmap createBitmap(byte[] bytes, int reqWidth, int reqHeight) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
opts.inSampleSize = getInSampleSize(opts, reqWidth, reqHeight);
opts.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
}
画像の読み込みに時間がかかることは気にしませんが、フラグメントが既に存在するすべてのテキスト情報とともに読み込まれ、ユーザーが断片。私の意見では、現在の状況はかなり悪いと思います.ユーザーが情報に写真をさらに添付すると、さらに悪化するのではないかと心配しています.