2017-01-19 54 views
0

所以1有2個ImageButtons,clothesButton1,圖像聲明爲xml,而imageButton2爲空。兩者都在分開的活動。 單擊clothesButton1後,我想使用位圖將圖像在clothesButton1中移動到imageButton2。 clothesButton1將在之後變爲空白。在單獨的圖像按鈕之間移動圖像活動onClick位圖

這是我在Java代碼clothesButton1

final ImageButton clothesButton1 =(ImageButton)findViewById(R.id.clothesBtn1); 

clothesButton1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

      clothesButton1.buildDrawingCache(); 
      Bitmap bitmapclothes = clothesButton1.getDrawingCache(); 
      Intent intent = new Intent(); 
      intent.putExtra("BitmapClothes", bitmapclothes); 
     } 
    }); 

在我的第二個活動(用於imageButton2):

final ImageButton imageButton2 = (ImageButton)findViewById(R.id.imageButton2); 
Intent intent = getIntent(); 
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapClothes"); 
imageButton2.setImageBitmap(bitmap); 

但是移動功能無法正常工作,我真的不知道在哪裏我錯了。任何幫助是極大的讚賞。

回答

0

這個錯誤是因爲意向。在android顯式和隱式意圖中有兩種類型的Intent。當您使用Context和Class對象創建一個Intent時,您正在創建一個明確的意圖。您使用顯式意圖在應用程序中啓動活動。當應用程序中的活動想要在另一個應用程序中啓動活動時,您將創建一個隱式意圖。在你的情況下,它是Explicit Intent使用Intent intent = new Intent(getApplicationContext(),secondActivityName.class)。 在你的情況

Intent intent=new Intent(getApplicationContext(),secondActivityName.class); 
intent.putExtra("BitmapClothes", bitmapclothes); 
startActivity(intent); 

要了解更多關於意圖read this tutorial

+0

非常感謝您的解釋和幫助!但是,我嘗試使用getContext(),但「無法解決方法」。所以我用getApplicationContext()來代替它。希望這並不意味着應用程序有太大的區別。 – xlayer

+0

是的,你的權利很高興它的幫助! – Yirga

0

首先,getDrawingCache()返回null;第二,您調用其他活動的方式不正確! 試試這個:

clothesButton1.setDrawingCacheEnabled(true); 
clothesButton1.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 
clothesButton1.layout(0, 0, clothesButton1.getMeasuredWidth(), imageButton.getMeasuredHeight()); 
clothesButton1.buildDrawingCache(true); 
Bitmap bitmapclothes = Bitmap.createBitmap(clothesButton1.getDrawingCache()); 
clothesButton1.setDrawingCacheEnabled(false); 
Intent intent = new Intent(NowActivity.this,SecondActivity.class); 
intent.putExtra("BitmapClothes", bitmapclothes); 
startActivity(intent); 

參考:Android View.getDrawingCache returns null, only null

+0

謝謝你的解釋和詳細的代碼!當然可以學習一些關於DrawingCache的新知識。你的代碼適用於我,但它比我的新解決方案稍長。如果其他人將來可能需要使用它,請立即投訴 – xlayer

+0

這是使用DrawingCache的最佳方式,您也可以自己在畫布上繪製視圖,就像參考中的第二個解決方案一樣,它也可以解決您的問題! –

0

我認爲,你可以很容易地Activity Transition實現這一目標。好好看看:) Start an activity with a shared element部分可能是你想要的。