我试图在我的应用中截取一个布局的屏幕截图。但是当我按下屏幕截图按钮时,App会崩溃。
日志:
05-05 23:17:29.000: E/AndroidRuntime(21992): FATAL EXCEPTION: main
05-05 23:17:29.000: E/AndroidRuntime(21992): java.lang.NullPointerException
05-05 23:17:29.000: E/AndroidRuntime(21992): at android.graphics.Bitmap.createBitmap(Bitmap.java:526)
05-05 23:17:29.000: E/AndroidRuntime(21992): at com.tiktak.babyalbum.Helper$8.onClick(Helper.java:298)
05-05 23:17:29.000: E/AndroidRuntime(21992): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:185)
05-05 23:17:29.000: E/AndroidRuntime(21992): at android.os.Handler.dispatchMessage(Handler.java:99)
05-05 23:17:29.000: E/AndroidRuntime(21992): at android.os.Looper.loop(Looper.java:137)
05-05 23:17:29.000: E/AndroidRuntime(21992): at android.app.ActivityThread.main(ActivityThread.java:5306)
05-05 23:17:29.000: E/AndroidRuntime(21992): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 23:17:29.000: E/AndroidRuntime(21992): at java.lang.reflect.Method.invoke(Method.java:511)
05-05 23:17:29.000: E/AndroidRuntime(21992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
05-05 23:17:29.000: E/AndroidRuntime(21992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
05-05 23:17:29.000: E/AndroidRuntime(21992): at dalvik.system.NativeStart.main(Native Method)
我使用Helper类来获得更干净的代码,这就是Helper Code Arround Line 298:
View u = act.findViewById(id);
u.setDrawingCacheEnabled(true);
LinearLayout z = (LinearLayout) act.findViewById(id);
int totalHeight = z.getHeight();
int totalWidth = z.getWidth();
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache(true);
298--> Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
String filePath = Environment.getExternalStorageDirectory()
+ File.separator + st1;
File myPath = new File(filePath);
FileOutputStream fos = null;
这是一种奇怪的情况,因为如果我在高级手机(如三星s4)上进行测试就会崩溃,但是如果我在低级手机上测试它(就像HTC野火版那样)它可以正常工作细
任何想法?
编辑:根据Goran评论,我检查了以这种方式返回null的内容:
View u = act.findViewById(id);
LinearLayout z = (LinearLayout) act.findViewById(id);
u.setDrawingCacheEnabled(true);
int totalHeight = z.getHeight();
int totalWidth = z.getWidth();
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache(true);
if (u.getDrawingCache() == null) {
Toast.makeText(act.getApplicationContext(), "DrawingCache is Null",
Toast.LENGTH_LONG).show();
} else {
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
String filePath = Environment.getExternalStorageDirectory()
+ File.separator + st1;
File myPath = new File(filePath);
并且在Wildfire S中,它有效,但在s4中我得到了#34; DrawingCatch为空"烤面包。
那么如何防止变为空?
答案 0 :(得分:0)
感谢this回答我通过使用此代码解决了我的问题:
CustomView view = (CustomView) findViewById(R.id.customViewId);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(),
view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bitmapHolder = new Canvas(bitmap);
view.draw(bitmapHolder);