我正在使用Xamarin和C#,但我怀疑问题在Java环境中同样有效。多个操作栏选项卡的屏幕截图
我有一个ActionBar活动,它承载三个选项卡,每个选项卡都承载一个片段。它使用ViewPager来允许用户在标签之间滑动。
要求是以编程方式截图每个选项卡,然后将这些作为附件通过电子邮件发送。
问题是,虽然ActionBar/ViewPager运行良好,但它也优化了选项卡 - 实际上它不会创建片段的视图,直到下一行显示为止。因此,如果您在选项卡0 - 第一个选项卡上 - 则选项卡2的片段视图为空。所以它不能截图。
为了克服这个问题,我尝试设置任何具有空视图的选项卡/片段进行选择。这会生成视图,但是因为将其设置为被选中并不实际在屏幕上显示它,所以视图没有宽度或高度值,因此它不能再截图(这是在代码开始时进行防御检查的原因截图)。
所以,我想我的问题是我如何强制在屏幕上呈现选项卡,以便它正确填写并可以截图?
我的主要代码提取如下:
private void EmailReport()
{
List <Bitmap> bitmaps = new List<Bitmap>();
List <string> summaryFiles = new List<string>();
// remember the tab we're on
var selectedTab = this.ActionBar.SelectedNavigationIndex;
// take the screenshots
for (int fragmentNumber = 0; fragmentNumber < projectFragmentPagerAdapter.Count; fragmentNumber++)
{
Android.Support.V4.App.Fragment fragment = projectFragmentPagerAdapter.GetItem(fragmentNumber);
if (fragment.View == null)
{
this.ActionBar.GetTabAt(fragmentNumber).Select();
fragment = projectFragmentPagerAdapter.GetItem(fragmentNumber);
}
bitmaps.Add(ScreenShot(fragment.View));
}
// set the active tab back
this.ActionBar.GetTabAt(selectedTab).Select();
//write the screenshots into file
int i = 0;
foreach(Bitmap bitmap in bitmaps)
{
if (bitmap != null)
summaryFiles.Add(BitmapToFile(bitmap, this.ActionBar.GetTabAt(i).Text));
i++;
}
// now send the file
EmailSupport.SendAttachments(this, summaryFiles);
}
private Bitmap ScreenShot(View fragmentRootView)
{
if (fragmentRootView == null || fragmentRootView.Width == 0 || fragmentRootView.Height == 0)
return null;
fragmentRootView.DrawingCacheEnabled = true;
//create a bitmap for the layout and then draw the view into it
Bitmap bitmap = Bitmap.CreateBitmap(fragmentRootView.Width, fragmentRootView.Height,Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
//Get the view's background
Drawable bgDrawable = fragmentRootView.Background;
if (bgDrawable!=null) // has background drawable, then draw it on the canvas
bgDrawable.Draw(canvas);
else // does not have background drawable, then draw white background on the canvas
canvas.DrawColor(Color.White);
// draw the view on the canvas
fragmentRootView.Draw(canvas);
fragmentRootView.DrawingCacheEnabled = false;
return bitmap;
}
任何帮助将受到欢迎。