set COMPLEX_UNIT_PX on Layout Parameters - android

I am developing for two different devices and need to force pxs on one device's layoutparameter object through code when specifying width and height. How do I do that?
GridView.LayoutParams glp = new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.WRAP_CONTENT);
glp.width = 80; <- need to ensure this is in px or LDPI interprets it .75 of 80
glp.height = 80;
Normally I would use setFontSize(TypedValue.COMPLEX_UNIT_PX, size) and it works. How about Layouts themselves?

You need the params to be fixed? If you want to make sure adding pixels, create dimen resources e.g: 80px in string.xml then load in LayoutParams
new GridView.LayoutParams(pixels, pixels); They are already pixels.
See the docs
http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html#ViewGroup.LayoutParams(int, int)

Related

Fix the Screen Size Issue Programmatically in Android

I was creating Android application. that will dynamically create questions. but based on the mobile screen size view is not coming properly. I don't know how to fix this problem. I have enclosed image that is taken form different mobiles.
Screen size -3.7" , Screen Size -5.0"
All the Element sizes are varied based on the screen size.can any one help to display responsive screen in Android.
My Code is:
lView.setBackgroundColor(Color.parseColor("#FFFFFF"));
lView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 220);
GradientDrawable gdtitle = new GradientDrawable();
gdtitle.setCornerRadius(5);
ImageView title = new ImageView(Main2Activity.this);
title.setImageResource(R.drawable.logo);
title.setLayoutParams(layoutParams2);
title.setBackgroundDrawable(gdtitle);
lView.setOrientation(LinearLayout.VERTICAL);
lView.addView(title);
GradientDrawable gd3 = new GradientDrawable();
gd3.setCornerRadius(30);
gd3.setColor(Color.parseColor("#003366"));
gd3.setStroke(0, 0xFF000000);
TextView uname1 = new TextView(Main2Activity.this);
uname1.setText("Hello , "+Sessionname);
uname1.setGravity(Gravity.LEFT);
uname1.setTextColor(Color.parseColor("#003366"));
uname1.setTextSize(20);
uname1.setLayoutParams(l2);
et1 = new TextView(Main2Activity.this);
et1.setHeight(100);
et1.setTextColor(Color.WHITE);
et1.setHintTextColor(Color.WHITE);
et1.setGravity(Gravity.CENTER);
et1.setHint("Select Date");
et1.setBackgroundDrawable(gd3);
et1.setTextSize(15);
et1.setLayoutParams(l2);
lView.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams l4 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
l4.gravity=Gravity.CENTER;
lHorizontalView1.setOrientation(LinearLayout.HORIZONTAL);
lHorizontalView1.setLayoutParams(l4);
lHorizontalView1.addView(uname1);
lHorizontalView1.addView(et1);
lView.addView(lHorizontalView1);
You're hard-coding your values in pixels. For example for your height you call setHeight(100) that means set this View to be 100px tall. However, with different screen densities that's going to look completely different. Given a fix screen size (say 5 inches), one device could have a resolution of 480x800 and another one could be 1440x2560, your setting of 100px will look exactly how you have it now.
Use Display Metrics instead to retrieve the screen density and use device independent pixels (dip or dp) instead of pixels (px) as units. For example you can set your height based on the density of the device like this:
setHeight(100 * getResources().getDisplayMetrics().density);
However, your desired height may have to be smaller as that will become 100dp so you may have to set it to something like 50 instead. Play around until you get your desired results.
then your View will look uniform across devices.

Why dpToPixel should not be used to set layout dimensions?

Why in javadocs for dpToPixel (declared here) is stated that it shouldn't be used to set layout dimensions?
We don't use pixels to define layout dimensions. Using density independent pixels ensures proper layout sizes across a variety of devices. Meaning said layout will have roughly the same visual size on a 4" phone and a 7" tablet. (Which is completely unrelated to the problem at hand :) )
That being said the actual layout sizes (e.g. LayoutParams class) are in fact using whole pixels to define the resulting size. It is viable to use the dpToPixels method in this way:
float px = dpToPixels(16, getResources()); // 16 dp to pixels precise
int pxOffset = (int) px; // 16dp rounded down to whole pixels
int pxSize = (int) (0.5f + px); // 16dp rounded up to whole pixels
Now you can use these values in layouts, pxOffset for padding, margin etc. (can be zero) and pxSize for width and height (ensures at least 1px size unless zero). The same calculation is done when using methods int Resources.getDimensionPixelOffset(int) and int Resources.getDimensionPixelSize(int) which are suitable for use with layouts and float Resources.getDimension(int) which is suitable for drawing precisely.
EDIT
Elevation uses float values so using the precise dimension is completely fine.
TranslationX, translationY or translationZ are defined using float values. These and many more view properties are used for animation so it makes sense to use smooth values. If set by hand use whole integers for predictable behavior.

Is there any difference between "TypedValue.COMPLEX_UNIT_DIP" and "dp in xml"?

In my App I am specifying the width of a few elements dynamically using
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, mycontext.getResources().getDisplayMetrics());
I am also using some other elements whose width are specified in the layout xml in dp terms.
However when I run the app on my Samsung Galaxy Grand, I observe that 100 dip specifed dynamically is not exactly equal to 100 dp specified in the layout xml(slightly more).
However, when I test it on a AVD it appears to be fine(both width matches).
Has anyone else encountered this issue as well?
Any Idea?
Found the issue.
I was doing :
int pixels_unit_five = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, mycontext.getResources().getDisplayMetrics());
Then I was using ths value for views with different widths like:
android.widget.RelativeLayout.LayoutParams params_item = new RelativeLayout.LayoutParams(pixels_unit_five*20,pixels_unit_five*8 );
android.widget.RelativeLayout.LayoutParams params_item = new RelativeLayout.LayoutParams(pixels_unit_five*10,pixels_unit_five*8 );
And so on..
The dip value is being cast to int and that was doing minor rounding off to fit the exact pixel value.This, when multiplied by 20 added up to a considerable difference in pixel value.
Solved it by obtaining exact dip value straightaway and using them.

how to set width of button with respect to the resolution available on android device

my current android project requires the width of button should be set dynamically depending on the resolution available on device
i want to arrange 9 button in a row but the size will depend on the resolution available
for the current scene we are using below code
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
//int sheight = displaymetrics.heightPixels;
int swidth = displaymetrics.widthPixels;
int px=swidth/11;
bW.setWidth(px);
bE.setWidth(px);
bR.setWidth(px);
bT.setWidth(px);
bY.setWidth(px);
bU.setWidth(px);
bI.setWidth(px);
bO.setWidth(px);
bP.setWidth(px);
somehow the width of button is not changed in any manner it remains the same
If i consider you buttons to be images, that you have set using the Selector file, then you need to keep those files in drawable-hdpi, drawable-mdpi, and drawable-ldpi, and the images will accomodate itself according to the available resolution..
i think you should use android:layout_weight property.Its going to consume space depending on the width available.
set to all the buttons as android:layout_weight="1"
Try this url
Linear Layout and weight in Android
Buttons and other objects that uses a ninepatch image won't get smaller than the ninepatch itself.
Make sure you are using an appropriate ninepatch image for you buttons that will fit the sizes you need.
i came up with this solution
ViewGroup.LayoutParams params = button.getLayoutParams();
params.width=px;
button.setLayoutParams(params);

Android set image size programmatically

How can I set the image size on a widget programmatically? I am using this code to change the image but how can I set the size?
RemoteViews updateViews = new RemoteViews(EditPreferences.this.getPackageName(), R.layout.widgetmain2);
updateViews.setImageViewBitmap(R.id.ImageView00, ((BitmapDrawable)EditPreferences.this.getResources().getDrawable(R.drawable.normal_black_op100)).getBitmap());
ComponentName thisWidget = new ComponentName(EditPreferences.this, HelloWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(EditPreferences.this);
manager.updateAppWidget(thisWidget, updateViews);
Thanks in advance
It's a very wide question in fact. There are multiple answers for it:
Usually you do it in layout.xml setting appropriate layout parameters (width, height) and scaleType: http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType. This handles a lot of cases - whenever the image is set its scaling will be recalculated according to it's parameters.
But sometimes you ned to do it programmatically. But it is more complex because it needs to take into account density of the screen and density of the bitmap, screen size independent pixel size and so on. There are two points here:
Getting bitmap in the right size. It depends whether you load bitmap from resources (it seems you do) or whether you load it manually. If you want to fully control the size of the bitmap, then you have to understand how it all works - I recommend reading http://developer.android.com/guide/practices/screens_support.html and especially the chapter Scaling Bitmap Objects created at Runtime.
Setting bitmap's dimensions on screen. If you want to do it on runtime and you already calculated required size in physical pixels. Remember there are also independent pixels and you need to convert physical pixels to another (look at "density independent pixels" definition and algorithms for calculation in http://developer.android.com/guide/practices/screens_support.html . Once you know the physical pixels, you can apply LayoutParameters to the ImageView. It will be something like:
Example:
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(width_physical_pixels, height_physical_pixels);
imageView.setLayoutParams(layoutParams);
IMPORTANT! LinearLayout here is just example. It should be the PARENT class of the ImageView - so layout params are always of the type of the object container rather than of the object they are set on.

Categories

Resources