【问题标题】:How to add “Set as” or “Set picture as” Option inside my android app ImageView如何在我的 Android 应用 ImageView 中添加“设置为”或“将图片设置为”选项
【发布时间】:2017-12-23 06:07:25
【问题描述】:

我的应用在图像视图中显示图像。我希望用户从应用程序本身中选择设置图片作为选项。 像这样

如何添加“设置为”弹出菜单,以便用户可以直接将图像设置为壁纸?图像已存储在 Drawable 文件夹中。

【问题讨论】:

标签: android android-imageview android-menu android-wallpaper


【解决方案1】:

您可以将以下代码用于“将图片设置为”。在这里,我正在截取当前活动的屏幕截图。然后我将该活动存储为位图。之后,我将提供该活动以意图“设置为选项”

点击按钮:

OnButtonClick(){
ImageProcessing imageProcessing = new ImageProcessing();
            Bitmap bitmap = imageProcessing.takeScreenshot(getWindow().getDecorView().findViewById(R.id.view_thought));
            imageProcessing.saveBitmap(bitmap);
            Intent intent = imageProcessing.setAsOption(this,imageProcessing.getSavedImagePath());
            startActivityForResult(Intent.createChooser(intent, "Set image as"), 200);
}

实现一个新类 ImageProcessing

public class ImageProcessing {
private File imagesPath;
public void saveBitmap(Bitmap bitmap) {
    imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagesPath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("POS", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("POS", e.getMessage(), e);
    }
}
public File getSavedImagePath(){
    imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
    return imagesPath;
}

public Bitmap takeScreenshot(View rootView) {
    rootView.setDrawingCacheEnabled(true);
    return rootView.getDrawingCache();
}
public Intent setAsOption(Context cntxt,File imagesPath){
    /*File imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");*/
    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    if(imagesPath.exists()){
        Uri contentUri = FileProvider.getUriForFile(cntxt, BuildConfig.APPLICATION_ID+".Utility.GenericFileProvider",imagesPath);

        intent.setDataAndType(contentUri, "image/jpg");
        intent.putExtra("mimeType", "image/jpg");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }else {
        Toast.makeText(cntxt,"Not a wallpaper",Toast.LENGTH_SHORT).show();
    }
    return intent;
}

}

在清单中添加:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-24
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多