【问题标题】:android: Generating Bitmap of layout throws NullPointerExceptionandroid:生成布局的位图抛出 NullPointerException
【发布时间】:2016-10-04 21:19:12
【问题描述】:

我有一个带有android:visibility="gone" 的线性布局。我想生成该布局的 png 文件。我的代码为 -

生成器函数-

public Bitmap viewToBitmap(View v) {
        v.setDrawingCacheEnabled(true);
        v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        v.buildDrawingCache(true);
        Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false);
        return b;
    }

主要代码-

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.share_layout);
                try {
                    Bitmap bitmap = viewToBitmap(linearLayout);
                    FileOutputStream output = new FileOutputStream(getExternalFilesDir(null)+ "/Image.png");
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
                    output.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

我收到以下错误@行:

Bitmap b = Bitmap.createBitmap(v.getDrawingCache());

java.lang.NullPointerException:尝试调用虚拟方法'int android.graphics.Bitmap.getWidth()' 在空对象引用上

我做错了什么?

编辑:这显然与问题不同-[What is a NullPointerException, and how do I fix it?.我知道 NullPointerException 是什么以及触发它的常见原因,但在这种情况下,我无法弄清楚为什么会有 NPE。

【问题讨论】:

标签: java android android-layout bitmap


【解决方案1】:

您必须等到系统生成您的视图。您可以通过以下方式设置监听器:

final View rootView = getWindow().getDecorView().getRootView();
rootView.getViewTreeObserver().addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
            @Override
            public void onDraw() {
                \\write your code here
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多