2017-01-19 60 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部分可能是你想要的。