Android程式設計權威指南(第2版)—第16章挑戰練習
阿新 • • 發佈:2019-01-06
16.7挑戰練習:優化照片顯示
(1)新建dialog_photo.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/crime_photo_detail" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
(2)新建PhotoDetailFragment.java
public class PhotoDetailFragment extends DialogFragment { private static final String ARG_File = "file"; private ImageView mPhotoView; public static PhotoDetailFragment newInstance(File file) { Bundle args = new Bundle(); args.putSerializable(ARG_File, file); PhotoDetailFragment fragment = new PhotoDetailFragment(); fragment.setArguments(args); return fragment; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { File file = (File) getArguments().getSerializable(ARG_File); View v = LayoutInflater.from(getActivity()) .inflate(R.layout.dialog_photo, null); mPhotoView = (ImageView) v.findViewById(R.id.crime_photo_detail); Bitmap bitmap = PictureUtils.getScaledBitmap( file.getPath(), getActivity()); mPhotoView.setImageBitmap(bitmap); return new AlertDialog.Builder(getActivity()) .setView(v) //.setTitle(R.string.date_picker_title) .setPositiveButton(android.R.string.ok, null) .create(); } }
(3)修改CrimeFragment.java
private static final int REQUEST_PHOTO = 3;
private static final String DIALOG_PHOTO = "DialogPhoto";
onCreateView增加處理
mPhotoView = (ImageView) v.findViewById(R.id.crime_photo); mPhotoView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mPhotoFile == null || !mPhotoFile.exists()) { mPhotoView.setImageDrawable(null); } else { FragmentManager manager = getFragmentManager(); PhotoDetailFragment dialog = PhotoDetailFragment.newInstance(mPhotoFile); dialog.setTargetFragment(CrimeFragment.this, REQUEST_PHOTO); dialog.show(manager, DIALOG_PHOTO); } } }); updatePhotoView();
16.8 挑戰練習:優化縮圖載入
修改CrimeFragment.java
(1)updatePhotoView,呼叫頻寬高參數的getScaledBitmap
private void updatePhotoView(int width, int height) {
if (mPhotoFile == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
Bitmap bitmap = PictureUtils.getScaledBitmap(
mPhotoFile.getPath(), width, height); // change this one
mPhotoView.setImageBitmap(bitmap);
}
}
(2)onCreateView加上
mPhotoObserver = mPhotoView.getViewTreeObserver();
mPhotoObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
updatePhotoView(mPhotoView.getWidth(), mPhotoView.getHeight());
}
});
return v;
(3)修改onActivityResult,不然返回拍完照片返回CrimeFragment的時候會顯示不出略縮圖
else if (requestCode == REQUEST_PHOTO) {
updatePhotoView(mPhotoView.getWidth(), mPhotoView.getHeight());
}
參考:點選開啟連結
上述程式碼執行無誤,可以達到效果,但是OnGlobalLayoutListener的原理還沒有太搞懂,只知道可以通過這個方式獲取檢視的寬和高,待以後深入學習後再加補充。