Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set width and height for custom view in programmatically?

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..

like image 798
SuReSh PaTi Avatar asked Dec 19 '11 06:12

SuReSh PaTi


3 Answers

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!

like image 164
Dimitris Makris Avatar answered Sep 23 '22 13:09

Dimitris Makris


Override the onMeasure() method, have a look here

like image 28
Walid Hossain Avatar answered Sep 23 '22 13:09

Walid Hossain


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.

like image 39
Mehdi Amirafshar Avatar answered Sep 19 '22 13:09

Mehdi Amirafshar