Android拍摄截图

Zac*_*lil 5 android screenshot bitmap

嗨,我试着编写一个截图的功能.我找到了一个代码,通过按钮clicklistner完美地完成它,但当我删除按钮clicklistner并尝试在oncreate中截取我获得的位图是空的.为什么会这样?

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/LinearLayout01"
>
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="munch"
    android:id="@+id/munchscreen"
    />
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="500dp"
    android:id="@+id/screenshots"

    />
Run Code Online (Sandbox Code Playgroud)

活动:

public class MainActivity extends Activity {
    LinearLayout L1;
    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);


        L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
        Button but = (Button) findViewById(R.id.munchscreen);
        but.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                View v1 = L1.getRootView();
                v1.setDrawingCacheEnabled(true);
                Bitmap bm = v1.getDrawingCache();
                BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                image = (ImageView) findViewById(R.id.screenshots);
                image.setBackgroundDrawable(bitmapDrawable);
            }
        });

    }


}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 3

只是尝试在 oncreate 中截取屏幕截图,我得到的位图是空的。为什么会发生这种情况?

UI 尚未呈现。鉴于您使用的方法,您需要框架实际绘制 UI,然后才能捕获屏幕截图。

相反,如果您拥有-backedView draw()的根,则可能已经在. 这取决于根是否已被调用,而且我不确定这种情况是否已经发生或稍后发生。BitmapCanvasonCreate()Viewmeasure()layout()onCreate()