【发布时间】:2023-03-20 14:52:01
【问题描述】:
如何将另一个片段的片段子视图导出为 Png?
上下文
我正在创建一个应用程序,它允许用户创建个性化的简历。用户可以提交有关他的工作经验和技能的信息。因此,用户能够将他的结果导出为 png 并将其保存到设备中。我的问题针对应用程序的导出功能。
到目前为止我得到了什么
我试图结合网站上的几个答案来获得结果,但不幸的是我的代码到目前为止还不起作用。
public void export(Context context) throws FileNotFoundException {
View exportView = getLayoutInflater(getArguments()).inflate(R.layout.fragment_form, null, false);
RelativeLayout subView = (RelativeLayout) exportView.findViewById(R.id.fragment_form_container_root);
try {
subView.setDrawingCacheEnabled(true);
subView.measure(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Bitmap b = Bitmap.createBitmap(subView.getDrawingCache(), 0, 0, subView.getMeasuredWidth(), subView.getMeasuredHeight());
File cachePath = new File(context.getCacheDir(), "images");
cachePath.mkdirs(); // don't forget to make the directory
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); // overwrites this image every time
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = FileProvider.getUriForFile(context, "com.example.lukas.masterthesis.fileprovider", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
shareIntent.setDataAndType(contentUri, getActivity().getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(shareIntent, "Choose an app"));
}
}
在点击事件之后在片段 A 中调用导出功能。我正在尝试获取 Fragment B 的所需子视图(似乎可行),但创建位图总是会导致 null 对象。因此程序失败。
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null
老实说,我什至不确定这是做这种事情的正确方法,因为我还没有找到适合我尝试的最佳实践解决方案。如果没有,有人知道更好的方法吗?
如果它是一个“好的”解决方案,是否有人知道如何让我的代码正常工作或有一些建议可以为我指明正确的方向?
提前致谢。
【问题讨论】:
标签: android xml android-fragments export png