我一直在尝试让这段代码在 fragment 中运行。此代码在 Activity 中运行良好,但我无法使其在 fragment 中运行。
当我点击一个按钮时,它会调用 takeScreenshot 方法。
这是截图的代码:
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
“findViewById”由于在 fragment 中而无法识别。
我试过:
View rootView = getView().findViewById(android.R.id.content).getRootView();
但它也不起作用。我明白了
07-25 09:37:32.746: E/AndroidRuntime(31221): FATAL EXCEPTION: main
07-25 09:37:32.746: E/AndroidRuntime(31221): java.lang.NullPointerException
07-25 09:37:32.746: E/AndroidRuntime(31221): at com.dream3ncore.thefinalwordcounts.level01.Song01.takeScreenshot(Song01.java:763)
07-25 09:37:32.746: E/AndroidRuntime(31221): at com.dream3ncore.thefinalwordcounts.level01.Song01.onClick(Song01.java:152)
07-25 09:37:32.746: E/AndroidRuntime(31221): at android.view.View.performClick(View.java:4211)
07-25 09:37:32.746: E/AndroidRuntime(31221): at android.view.View$PerformClick.run(View.java:17362)
07-25 09:37:32.746: E/AndroidRuntime(31221): at android.os.Handler.handleCallback(Handler.java:725)
07-25 09:37:32.746: E/AndroidRuntime(31221): at android.os.Handler.dispatchMessage(Handler.java:92)
07-25 09:37:32.746: E/AndroidRuntime(31221): at android.os.Looper.loop(Looper.java:137)
07-25 09:37:32.746: E/AndroidRuntime(31221): at android.app.ActivityThread.main(ActivityThread.java:5227)
07-25 09:37:32.746: E/AndroidRuntime(31221): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 09:37:32.746: E/AndroidRuntime(31221): at java.lang.reflect.Method.invoke(Method.java:511)
07-25 09:37:32.746: E/AndroidRuntime(31221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
07-25 09:37:32.746: E/AndroidRuntime(31221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
07-25 09:37:32.746: E/AndroidRuntime(31221): at dalvik.system.NativeStart.main(Native Method)
任何帮助将不胜感激。
最佳答案
Fragment
的 UI 是 Activity
的 UI 的子集。 Fragment
中的 getView()
将仅返回其自己的 View 层次结构。您可以将对 getView()
的调用更改为 getActivity()
,这样就可以了。或者,我相信您可以直接调用 getView().getRootView()
并首先避免查找 android.R.id.content
。
关于android - Fragment里面的截图方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24944480/