How to resize a custom view programmatically?

herbertD picture herbertD · Jun 3, 2010 · Viewed 254k times · Source

I am coding a custom view, extended from RelativeLayout, and I want to resize it programmatically, How can I do?

the custom view Class is something like:

public ActiveSlideView(Context context, AttributeSet attr){
        super(context, attr);
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if(inflater != null){       
            inflater.inflate(R.layout.active_slide, this);
        }

Answer

smisiewicz picture smisiewicz · Feb 10, 2011

Android throws an exception if you fail to pass the height or width of a view. Instead of creating a new LayoutParams object, use the original one, so that all other set parameters are kept. Note that the type of LayoutParams returned by getLayoutParams is that of the parent layout, not the view you are resizing.

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) someLayout.getLayoutParams();
params.height = 130;
someLayout.setLayoutParams(params);