开发者

Android - canvas onDraw does not fire

开发者 https://www.devze.com 2023-04-12 07:32 出处:网络
I am trying to add a canvas view to a relative layout inside a horizontal scroll view. <?xml version=\"1.0\" encoding=\"utf-8\"?>

I am trying to add a canvas view to a relative layout inside a horizontal scroll view.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#fff"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    &l开发者_如何学Got;HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/hsv"
        android:layout_width="fill_parent"
        android:background="#EEDB00"
        android:layout_height="30mm">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/canvas"
            android:background="#000"
            android:layout_width="300mm"
            android:layout_height="20mm">
        </RelativeLayout>

    </HorizontalScrollView>
</RelativeLayout>

I created a class called CanvasView which extends View, and I drew some basic shapes by over-riding onDraw(). However the canvas does not appear in the relativelayout, when I do:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        cView = new CanvasView(this);
        rLayout = (RelativeLayout)this.findViewById(R.id.canvas);
        rLayout.addView(cView);
    }

However, when I directly add it by calling setContentView(cView); it works. On digging, I found that when I call addView(), the onDraw() is not firing at all, and hence the canvas is not drawn... Any ideas on how to fix this?


I'm not in a position to test this myself at the moment, but I think your problem is that you're not applying any LayoutParams to the View, which may mean it occupies no screen space. If a View is ever off-screen or completely obscured or the system otherwise decides that nothing it draws will be visible, then I believe onDraw() won't be called at all.

Try setting some width and height to your View when you add it to your RelativeLayout:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50,50);
rLayout.addView(cView, params);    
0

精彩评论

暂无评论...
验证码 换一张
取 消