RelativeLayout转Bitmap时share_footer未显示的问题求助
Hey there, let's dig into why your share_footer is visible on the screen but missing from the Bitmap generated from screen_shot_relative_layout.
The Root Cause
When you switch share_footer from GONE to VISIBLE, Android's UI framework needs to run through three key steps for that view: measure, layout, and draw. These operations happen asynchronously on the UI thread. If you trigger the Bitmap creation immediately after setting visibility, the system hasn't finished updating the layout yet—so the share_footer doesn't get drawn into the Bitmap.
Solution 1: Use View.post() to Wait for Layout Completion
The simplest fix is to wrap your Bitmap generation code in a post() call. This adds your code to the end of the UI thread's message queue, ensuring it runs after all pending layout updates are done.
Here's how to adjust your code:
// First, make share_footer visible share_footer.setVisibility(View.VISIBLE); // Get the target RelativeLayout RelativeLayout screenShotLayout = findViewById(R.id.screen_shot_relative_layout); // Post the screenshot logic to run after layout finishes screenShotLayout.post(new Runnable() { @Override public void run() { // Generate the Bitmap Bitmap bitmap = Bitmap.createBitmap( screenShotLayout.getWidth(), screenShotLayout.getHeight(), Bitmap.Config.ARGB_8888 ); Canvas canvas = new Canvas(bitmap); screenShotLayout.draw(canvas); // Proceed with your share logic bitmapUri = Uri.parse(...); // Rest of your share code here } });
Solution 2: Manually Trigger Measure & Layout (If post() Doesn't Work)
In some edge cases (like if the parent layout's size is also changing), you might need to manually force the view to measure and layout itself before taking the screenshot:
share_footer.setVisibility(View.VISIBLE); RelativeLayout screenShotLayout = findViewById(R.id.screen_shot_relative_layout); // Force the view to measure its desired size int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); screenShotLayout.measure(widthMeasureSpec, heightMeasureSpec); // Lay out the view with the measured dimensions screenShotLayout.layout( 0, 0, screenShotLayout.getMeasuredWidth(), screenShotLayout.getMeasuredHeight() ); // Now generate the Bitmap Bitmap bitmap = Bitmap.createBitmap( screenShotLayout.getMeasuredWidth(), screenShotLayout.getMeasuredHeight(), Bitmap.Config.ARGB_8888 ); Canvas canvas = new Canvas(bitmap); screenShotLayout.draw(canvas); // Continue with share logic bitmapUri = Uri.parse(...);
Key Notes
- Always run these operations on the UI thread—View measurement, layout, and drawing can't be done on background threads.
- If you're working in a Fragment, make sure you're executing this code after
onViewCreated()(so the views are fully initialized).
内容的提问来源于stack exchange,提问作者AkshayT

