【发布时间】:2014-06-29 23:47:40
【问题描述】:
我尝试创建一个屏幕截图应用程序,但不知何故我无法获取根内容。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
public class Screenshot extends Activity {
public final String TAG = "Screen";
String output;
public String takeScreen(String savepathname) {
Log.e(TAG, "TAKESCREEN 01");
//View content = findViewById(R.id.button1);
//View content = findViewById(R.id.layoutroot);
//View content = getWindow().getDecorView().findViewById(android.R.id.content);
Log.e(TAG, "TAKESCREEN 01.5");
content.setDrawingCacheEnabled(true);
Log.e(TAG, "TAKESCREEN 02");
//View content = findViewById(R.id.layoutroot);
Bitmap bitmap = content.getDrawingCache();
File file = new File( Environment.getExternalStorageDirectory() + savepathname);
Log.e(TAG, "TAKESCREEN 03");
try{
Log.e(TAG, "TAKESCREEN 04");
file.createNewFile();
Log.e(TAG, "TAKESCREEN 05");
FileOutputStream ostream = new FileOutputStream(file);
Log.e(TAG, "TAKESCREEN 06");
bitmap.compress(CompressFormat.PNG, 100, ostream);
Log.e(TAG, "TAKESCREEN 07");
ostream.close();
output = "Successfully saved -> "+savepathname;
}catch (Exception e) {
e.printStackTrace();
output = "Screenshot.java -> "+e;
}
return output;
}
}
如果我使用 findViewbyId,我只会收到此错误:“layoutroot 无法解析或不是字段”。
使用“getWindow().getDecorView().findViewById(android.R.id.content);”时有效,但随后应用程序在该部分崩溃。
有人可以帮我吗?
【问题讨论】:
-
onCreate()方法在哪里?您需要在该方法中调用 setContentView()。 -
setContentView(R.layout.main);在另一个班级。我发布的那个课程应该只用于截屏。我也已经尝试将视图内容定义为使用 onCreate() 的主类中的函数,但如果我在其他类中使用此函数,则结果完全相同。
-
屏幕类扩展
Activity。也许你正在尝试的是可行的,IDK,但我相信这是不好的做法。如果您想使用视图,则需要在定义它的位置显示活动。
标签: android crash screenshot