2015-03-03 26 views
1

我想设计一个带截图功能的应用程序。 这是我的课:ActionBarView只能用于android:layout_height =“match_parent”

public class ScreenShot { 

private static Bitmap takeScreenShot(Activity activity) { 

    View view = activity.getWindow().getDecorView(); 
    view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
    // view.setDrawingCacheEnabled(true); 
    view.buildDrawingCache(); 
    Bitmap b1 = view.getDrawingCache(); 

    if (null == b1 || b1.getHeight() == 0 || b1.getWidth() == 0) { 
     System.out.println("b1 is null"); 
    } else { 
     System.out.println("b1 is NOT null"); 
    } 

    view.destroyDrawingCache(); 
    return b1; 
} 


private static void savePic(Bitmap b, String strFileName) { 
    FileOutputStream fos = null; 
    try { 
     fos = new FileOutputStream(strFileName); 
     if (null != fos) { 
      b.compress(Bitmap.CompressFormat.PNG, 90, fos); 
      fos.flush(); 
      fos.close(); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


public static void shoot(Activity a) { 
    File sdcardDir = null; 
    boolean isSDExist = Environment.getExternalStorageState().equals(
      Environment.MEDIA_MOUNTED); 
    if (isSDExist) { 
     sdcardDir = Environment.getExternalStorageDirectory(); 
    } else { 
     sdcardDir = null; 
    } 
    String file = sdcardDir + "/xx.png"; 
    System.out.println(file); 
    ScreenShot.savePic(ScreenShot.takeScreenShot(a), file); 
    } 
} 

但它也有一些错误:java.lang.IllegalStateException: ActionBarView can only be used with android:layout_height="match_parent"; 我不知道为什么会发生这种情况,并且我没有使用ActionBarView。我的布局只有一个textview和一个relativelayout。

有一个错误日志:03-03 10:56:09.530: E/AndroidRuntime(20452): at android.view.View.measure(View.java:12912);可能是view.measure()有错我用过?

回答

0

`View view = activity.getWindow()。getDecorView(); 这将检索顶层窗口的装饰认为,包括动作条和动作条只能用身高= match_parent

使用。如果你不想使用动作条,你必须使用一个NoActionBar主题(如Theme.Holo。 Light.NoActionBar)

或者由-1

view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

+0

我必须尝试改变而改变在下面的代码值0 0到-1,但是错误在那里。但我解决了这个问题。对view.getDrawingCache()使用'view.measure'总是返回null。我发现null返回来自布局不加载整个,所以如果我在onClickListener中添加按钮和屏幕截图,一切都可以。 但结果不是我想要的。所以我必须尝试其他的东西。 – Cheng 2015-03-04 01:26:33