How to get the drawable from relative layout in an

2020-05-06 09:19发布

问题:

What i have done: I have set the bitmap for a relative layout as below

RelativeLayout root;
root= (RelativeLayout) itemView.findViewById(R.id.root);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap preview_bitmap = BitmapFactory.decodeResource(context.getResources(),godImages[position], options);
Drawable drawable = new BitmapDrawable(context.getResources(),preview_bitmap);
root.setBackgroundDrawable(drawable);

What i am trying to do: I am trying to get the bitmap from the relativelayout back again that was set so that i can pass to another activity.

Note: i am aware of using the intents to padd data between activities only i want to know how to get the bitmap

Any ideas on How to achieve this ?

回答1:

There are a couple of ways you can do this:

1. Try:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.rel);
layout.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(layout.getDrawingCache());
layout.setDrawingCacheEnabled(false);

2. Or try:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.rel);
Bitmap b = Bitmap.createBitmap( layout.getLayoutParams().width, layout.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
Canvas c = new Canvas(b);
layout.layout(layout.getLeft(), layout.getTop(), layout.getRight(), layout.getBottom());
layout.draw(c);

To get the current ImageView

1. To get current position, use

ViewPager viewPager = getView().findViewById(r.id.pager);
int position = viewPager.getCurrentItem();

2. To get the current View, use

View currentView = viewPager.getChildAt(int position);

This currentView is the View created by the onCreateView() method of the current Fragment.

3. To get the ImageView, use

ImageView currentImage = (ImageView)currentView.findViewById(R.id.image);

where R.id.image is the ImageView object you want from the current Fragment.