-1
我知道有很多這樣的帖子,但我的是一個有點特別。Android - ImageView/ImageButton與畫廊或相機的圖像
問題描述:
我希望有一個公共類,顯示一個小對話框,選擇圖像源,相機或畫廊。選擇後,ImageView將顯示圖像,圖像將保存在應用程序文件夾中。這個課程將從許多活動中調用。所以,我有這樣的代碼:
PhotoActivity.java
package com.app.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.MediaStore;
import java.util.ArrayList;
import java.util.List;
public class PhotoActivity {
private Context context;
public PhotoActivity(Context current){
this.context = current;
}
//this will be called from other activities
public void Change_Photo(final Activity a) {
List<String> options = new ArrayList<String>();
options.add(context.getResources().getString(R.string.camera));
options.add(context.getResources().getString(R.string.gallery));
options.add(context.getResources().getString(R.string.cancel));
//Create sequence of items
final CharSequence[] Sources = options.toArray(new String[options.size()]);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(context.getResources().getString(R.string.select_image_source));
dialogBuilder.setItems(Sources, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item==0) {//camera
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
a.startActivityForResult(takePicture, 0);//zero can be replaced with any action code
}else if (item == 1) {//gallery
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
a.startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
}
});
//Create alert dialog object via builder
AlertDialog alertDialogObject = dialogBuilder.create();
//Show the dialog
alertDialogObject.show();
}
}
我加在清單文件:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
其他activites有一個ImageView的或ImageButton的是這樣的:
<ImageButton
android:id="@+id/btn_picture"
android:layout_width="140dp"
android:layout_height="140dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:elevation="0dp"
android:gravity="center_horizontal"
android:src="@drawable/camera" />
它在開始時有相機圖像,但會s最終如何選擇圖像。
下一步必須做什麼才能顯示此ImageButton中選定或拍攝的照片?
比getBitmap()和setImageBitmap()更好的選擇是使用[圖像加載庫](https://android-arsenal.com/tag/46),如畢加索。答案中顯示的代碼在主應用程序線程上加載圖像,這會凍結UI。 – CommonsWare
這樣做的工作。一個小問題。當我拍攝一張新照片時,ImageButton顯示它向左旋轉90度。爲什麼? –
這取決於照片的大小,拍一張小照片,然後重試 –