How to set width and height for custom view programmatically?

I created a custom view called 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 added the view to the XML file using the package name. It is working fine. Now I want to set the height and width at runtime of MyDraw, for this I used the following code,

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

but I got an exception for example

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

How to solve this exception? please help me..

+6
source share
2 answers

Override the onMeasure() method, see here

+9
source

You must override the onMeasure () method for the view.

For a good 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 here: http://marakana.com/forums/android/general/563.html

Hope this helps!

+18
source

Source: https://habr.com/ru/post/904056/


All Articles