Skip navigation

linux_android_iphone1

Ever been vexed by defining layout parameters in android views via the “new LayoutParams(LayoutParams.whatever,LayoutParams.whatever)” syntax you see all over the place? Well I certainly am, and it’s also bad practice for runtime performance since you use the ‘new’ operator repeatedly for essentially the same task.

Below follows a convenience class for defining simple layout parameters:


import android.view.ViewGroup.LayoutParams;

public class DefineLayoutParams {
//the controls
private static final int MATCHMATCH = 1;
private static final int WRAPMATCH = 2;
private static final int MATCHWRAP = 3;
private static final int WRAPWRAP = 4;

//the ONE layoutparams object
private static LayoutParams floatParams = new LayoutParams(0,0);

public DefineLayoutParams(){

}

public static LayoutParams getParams(int type){
if (type == MATCHMATCH){
floatParams.width = LayoutParams.MATCH_PARENT;
floatParams.height = LayoutParams.MATCH_PARENT;
}
else if(type == WRAPWRAP){
floatParams.width = LayoutParams.WRAP_CONTENT;
floatParams.height = LayoutParams.WRAP_CONTENT;
}
else if (type == WRAPMATCH){
floatParams.width = LayoutParams.WRAP_CONTENT;
floatParams.height = LayoutParams.MATCH_PARENT;
}
else if (type == MATCHWRAP){
floatParams.width = LayoutParams.MATCH_PARENT;
floatParams.height = LayoutParams.WRAP_CONTENT;
}
return floatParams;
}

public static LayoutParams getCustomParams(int w, int h){
floatParams.width = w;
floatParams.height = h;
return floatParams;
}

public static int getMM(){
return MATCHMATCH;
}
public static int getWW(){
return WRAPWRAP;
}
public static int getWM(){
return WRAPMATCH;
}
public static int getMW(){
return MATCHWRAP;
}

}

Once this class is added to your project’s src directory, use it like so–
1. [predefined] hActivity.addContentView(hView,DefineLayoutParams.getParams(DefineLayoutParams.getWW()));
2.[custom] hActivity.addContentView(hView,DefineLayoutParams.getCustomParams(150,250));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: