1

So I have the following layout called demo_text.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/screen">

<TextView
    android:id="@+id/textToDisplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Hello World"
</FrameLayout>

I am trying to convert this demo_text to a Bitmap. This is my onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    View inflatedFrame = getLayoutInflater().inflate(R.layout.demo_text, null);
    FrameLayout frameLayout = (FrameLayout) inflatedFrame.findViewById(R.id.screen) ;
    frameLayout.setDrawingCacheEnabled(true);
    frameLayout.buildDrawingCache();
    Bitmap bm = frameLayout.getDrawingCache();

}

I want the bitmap to be the entire layout but the Bitmap is always returning null.

NodeJSNoob
  • 117
  • 1
  • 7
  • Why are you using `FrameLayout` as root of your view in your Activity? You may use `FrameLayout` in a `Fragment`. Anyways, you can try to pass the root `ViewGroup` at 2nd argument in `inflate` method instead of `null`. (not sure if this works) – lalosoft Aug 01 '17 at 00:44
  • Duplicate https://stackoverflow.com/a/12406426/2700586 – Mani Aug 01 '17 at 00:49

2 Answers2

6

The following code works:

    View inflatedFrame = getLayoutInflater().inflate(R.layout.demo_text, null);
    FrameLayout frameLayout = (FrameLayout) inflatedFrame.findViewById(R.id.screen) ;
    frameLayout.setDrawingCacheEnabled(true);
    frameLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    frameLayout.layout(0, 0, frameLayout.getMeasuredWidth(), frameLayout.getMeasuredHeight());
    frameLayout.buildDrawingCache(true);
    final Bitmap bm = frameLayout.getDrawingCache();
NodeJSNoob
  • 117
  • 1
  • 7
0

You can try with below code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
FrameLayout frameLayout = (FrameLayout) inflatedFrame.findViewById(R.id.screen);  
Bitmap b  = loadBitmapFromView(frameLayout);
}

use belolw method to get bitmap.

public  Bitmap loadBitmapFromView(View v) {
    Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, 
    v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
    Canvas c = new Canvas(b);
    v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    v.draw(c);
    return b;
}
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43