2014-12-02 79 views
0

我正在使用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; 
    } 

任何幫助將受到歡迎。

回答

0

最終的解決方案非常簡單。 ViewPager有一個控制頁面(片段)數量的設置,它將保持「激活」。這默認爲1.因爲我有3個標籤,這意味着總是有一個標籤(片段)遙不可及。

所以,雖然建立ViewPager做添加標籤之前執行以下操作:

reportViewPager.OffscreenPageLimit = pageCount - 1; 

或者在Java中

reportViewPager.setOffscreenPageLimit(pageCount - 1); 

我希望這可以幫助別人避免浪費時間。