Question

I am trying to add a View to ViewGroup on ViewGroup's onTouchEvent, following is the code:

        ViewGroup mDrawingCanvas = new ViewGroup(mContext) 
        {
            @Override
            public boolean isFocused() {
                // TODO Auto-generated method stub
                Log.d(TAG, "View's On focused is called !");
                return super.isFocused();
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                // TODO Auto-generated method stub

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    View vv = new View(mContext);
                    vv.setBackgroundColor(Color.GREEN);
                    vv.setLayoutParams(new LayoutParams(200, 200));
                    this.addView(vv);

                    Toast.makeText(mContext, "Views child count = "+this.getChildCount(), Toast.LENGTH_SHORT).show();;

                    break;

                return true;
            }

            @Override
            protected void onLayout(boolean changed, int l, int t, int r,
                    int b) {
                // TODO Auto-generated method stub

            }
        };

The View is being added to the Viewgroup, Toast displays greater View count on every Touch Down Event, but the View is not being displayed on Screen in the ViewGroup.
I have seen related question on StackOverflow, but my question is unique and different.
Please guide me on how to solve this problem, any help is highly appreciated.

P.S: I have also tried to set the Layout params of the View before adding it to the ViewGroup, but am getting the same results. I have also printed the View's width and Height in LogCat after adding it to the ViewGroup and it always displays 0. I think that the problem is somewhere with the settings of Width and Height of the View.

Was it helpful?

Solution

If you are using a custom ViewGroup, you have to implement the onLayout method to display anything.

ViewGroup is just a base class for other layouts, it does not do anything by itself. I would advise to use one of its descendant, like FrameLayout or LinearLayout.


If you are creating a drawing application, you might be better using a Canvas instead of using a custom layout. Canvas already provides several methods to draw lines, circles, rectangles, etc. You will have some work to do if you want to be able to move one element afterwards though.

Draw with a Canvas

OTHER TIPS

You should to define how children views will show in your ViewGroup in onLayout method. If you don't need some special view, try to use FrameLayout instead ViewGroup

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top