7

I have created a custom view named MyDraw ,this is my MyDraw code,

public class MyDraw extends View {


    public MyDraw(Context context) {
        super(context);

    }

    public MyDraw(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    public MyDraw(Context context, AttributeSet attrs) {
        super(context, attrs);

    }
         ........................................
}

I have added the view in XML file using package name. It is working fine. Now I want to set height and width for the MyDraw in run time,for that i have used following code,

mMyDraw.setLayoutParams(new LayoutParams(220, 300));

but i got Exception like,

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams

How to solve this exception? please help me..

Vivek Kalkur
  • 2,200
  • 2
  • 21
  • 40
SuReSh PaTi
  • 1,373
  • 7
  • 28
  • 46
  • 1
    Possible duplicate of [Android set height and width of Custom view programmatically](http://stackoverflow.com/questions/5042197/android-set-height-and-width-of-custom-view-programmatically) – e-sushi Nov 19 '16 at 12:44

3 Answers3

22

You must override the onMeasure() method of the View.

For a nice example you can check here: http://kahdev.wordpress.com/2008/09/13/making-a-custom-android-button-using-a-custom-view/

And a very cool video that I would recommend is here: http://marakana.com/forums/android/general/563.html

Hope this helps!

Dimitris Makris
  • 5,183
  • 2
  • 34
  • 54
  • 1
    Isn't it the same answer as mine? Do you think adding some other link is making it different answer? – Walid Hossain Dec 19 '11 at 07:11
  • 4
    When started writing the answer, you hadn't answer yet. If you feel better if I remove the answer I have no problem. In any case the user can vote your answer. – Dimitris Makris Dec 19 '11 at 07:14
  • If you think you need not to remove the answer I've no problem. In fact a lot of time I faced same thing (Someone answered while I was writing the same) :) – Walid Hossain Dec 19 '11 at 07:17
  • 3
    Adding extra links does help indeed. Look at the vote count :) – Elye Jan 20 '16 at 01:02
11

Override the onMeasure() method, have a look here

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Walid Hossain
  • 2,724
  • 2
  • 28
  • 39
1

There is a simple way: based on our custom view parent class we can use layout param.

for example if our custom view is extended from FrameLayout:

FrameLayout.LayoutParams params = (LayoutParams) findViewById(R.id.root).getLayoutParams();
params.width = newwidth;
params.height = newHeight;
setLayoutParams(params);

where "R.id.root" is id of our root view in custom_view.xml that in this case is FrameLayout.