[英]Passing Picture from one activity to another activity
當我單擊網格視圖中的某個項目並將其轉到另一個活動並在此處查看其代碼時,便有了一個網格視圖,如下所示:
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
我要查看的活動
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("s");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(imageAdapter.moodpic[position]);
您嘗試在此處用getInt("s")
錯誤的鍵獲取Extra。
嘗試這個
int position = getIntent().getIntExtra("id",0);
你應該改變
int position = i.getExtras().getInt("id" , 0);
相反,這
int position = i.getExtras().getInt("s");
這是因為您已將“ id ”作為鍵,因此無論何時檢索,該鍵都必須相同,並且默認情況下int的值為0 。
首先將圖像轉換為字節數組,然后傳遞到Intent,然后在下一個活動中從Bundle中獲取字節數組,然后轉換為Image(Bitmap)並設置為ImageView。
將位圖轉換為字節數組:
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// Bitmap bmp = BitmapFactory.decodeFile(path); You can use this also.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
將字節數組傳遞給意圖:
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
從捆綁中獲取字節數組並轉換為位圖圖像:-
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
2)首先將圖像保存到SDCard,然后在下一個活動中將此圖像設置為ImageView。
3)將位圖傳遞到Intent並從包中的下一個活動中獲取位圖,但是問題在於,如果那時您的位圖/圖像大小很大,則無法在下一個活動中加載圖像。
我強烈建議采用其他方法。 如果您確實想這樣做,則可能會發生,但它會占用大量內存,而且速度很慢。 如果您的手機較舊且位圖較大,則可能無法正常工作。 例如,您可以額外傳遞它
intent.putExtra("data", bitmap)
位圖實現了Parcelable,因此您可以額外添加它。 同樣,一個包具有您想在活動之間傳遞的putParcelable
f,我會將其存儲在文件中。 這樣可以提高效率,減少工作量。 您可以使用MODE_PRIVATE在數據文件夾中創建私有文件,而其他任何應用程序都無法訪問這些私有文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.