簡體   English   中英

Android:與其他應用程序共享可繪制資源

[英]Android : Share drawable resource with other apps

在我的活動中,我有一個ImageView。 我想要,當用戶單擊它時,會打開一個對話框(如意圖對話框),該對話框顯示可以打開圖像的應用程序列表,而不是用戶可以選擇一個應用程序並顯示該應用程序的圖像。

我的活動代碼:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ImageView iv = (ImageView) findViewById(R.id.imageid);
    iv.setImageResource(R.drawable.dish);
    iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //here is where I want a dialog that I mentioned show
                }
    });
}// end onCreate()

您不能將位圖傳遞給意圖。

從我的角度來看,您希望共享資源中的可繪制對象。 因此,首先您必須將drawable轉換為位圖。 然后,您必須將位圖作為文件保存到外部存儲器,然后使用Uri.fromFile(new File(pathToTheSavedPicture))獲取該文件的uri,並將該uri傳遞給這樣的意圖。

shareDrawable(this, R.drawable.dish, "myfilename");

public void shareDrawable(Context context,int resourceId,String fileName) {
    try {
        //convert drawable resource to bitmap
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);

        //save bitmap to app cache folder
        File outputFile = new File(context.getCacheDir(), fileName + ".png");
        FileOutputStream outPutStream = new FileOutputStream(outputFile);
        bitmap.compress(CompressFormat.PNG, 100, outPutStream);
        outPutStream.flush();
        outPutStream.close();
        outputFile.setReadable(true, false);

        //share file
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
        shareIntent.setType("image/png");
        context.startActivity(shareIntent);
    } 
    catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
    }
}

您必須使用Intent.ACTION_VIEW類型的Intent.ACTION_VIEW startActivity

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(<your_image_uri>, "image/*");
            startActivity(intent); 
Create a chooser by using the following code. You can add it in the part where you say imageview.setonclicklistener(). 
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM