如何避免在自定义视图的onDraw中调用bringToFront()?

时间:2015-05-30 21:30:57

标签: android

我有一个自定义视图,您可以在activity_main.xml中看到。现在它隐藏在相机片段下面。我想让它出现在它之上。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
<com.snappiesticker.cwac4.StickerView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
    </FrameLayout>

这是班级本身:

public class StickerView extends View {

    Bitmap bitmap;

    float x = 2;
    float y = 2;

    public StickerView(Context context, AttributeSet attrs) {
        super(context,attrs);
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.paunch);
    }


    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, x, y, null);
        // I wanted to put it here but that would cause the loop described below.  
    }


}

循环,我的意思是:onDraw被调用,它调用bringToFront,它要求重新呈现布局。调用onDraw,调用bringToFront等等。

这是我想要避免的。

这是在mainActivity中实例化的。

public class MainActivity extends Activity implements CameraHostProvider {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        DemoCameraFragment current = new DemoCameraFragment();

        getFragmentManager().beginTransaction()
                .add(R.id.fragment_container, current)
                .commit();
        // can I somehow tell it to render the custom sticker view at the front here?
    }
}

1 个答案:

答案 0 :(得分:1)

我是否理解正确,您希望将自定义 StickerView 保留在相机片段之上?如果是这种情况,您可以简单地将布局细化为类似的东西;

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <com.snappiesticker.cwac4.StickerView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

使用此布局,您的相机片段会添加到 StickerView 下方,并且根本不需要调用 bringToFront()。如果您将根布局用作片段容器,则会在自定义视图之后添加片段,即在其上方。