dynamic EditText different size in different resolutions - java

for(int l=0;l<c.getCount();l++)
{
EditText etpob = new EditText(this.getActivity());
etpob.setInputType(InputType.TYPE_CLASS_NUMBER);
int po=Integer.parseInt("1" + c.getInt(3)) ;
etpob.setId(po);
etpob.setHint("POB");
etpob.setText("");
etpob.setTextSize(15);
etpob.setVisibility(View.VISIBLE);
etpob.setLayoutParams(new LinearLayout.LayoutParams(0, 50, 15));
etpob.setGravity(Gravity.RIGHT);
}
I have added the EditText dynamically above is my code, But it resolution fails out for different types of screen,in layout using styles we can change it out.

You can use dimension for setting width of dynamic generated edittext
int pixels = 15; // use dimen here
float scale = getContext().getResources().getDisplayMetrics().density;
float dips = pixels / scale;
So,
etpob.setLayoutParams(new LinearLayout.LayoutParams(0, pixels , pixels ));
or if it is require you can set dimen and than you can do it like this way
getContext().getResources().getDimension(R.dimen.activity_horizontal_margin); //set size of dimen in required resolution

You can do the same way.
Define the parameters in style files and use it in code.
Check below link for reference
How to retrieve style attributes programmatically from styles.xml

if you want to use an static integer in your code for size of your EditText, must use values folder in different sizes.
create in res folder these folders: values-small, values-normal,values-large,values-xlarge.
in these folder make a resources file with Integer values. like below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="edittext_width">70</integer>
<integer name="edittext_height">30</integer>
</resources>
you can set this values with same name but different values in these folders.
then, you must use it in your code:
etpob.setLayoutParams(new LinearLayout.LayoutParams(0, getResources().getInteger(R.integer.edittext_width), getResources().getInteger(R.integer.edittext_height)));
GOOD LUCK.

Incase the editText needs to match_parent
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
width = size.x;
And set width to EditText
editText.setWidth(width);

etpob.setLayoutParams(new LinearLayout.LayoutParams(0, ConvertPixels(50), ConvertPixels(15)));
public int ConvertPixels(int ht)
{
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,ht, getActivity().getResources().getDisplayMetrics());
return height;
}
Used existing utility method built called TypedValue.applyDimensions(int, float, DisplayMetrics)

Related

What units are applied when declaring a view programmatically?

When adding a view in an axml file, it is possible to simply specify the size and the units of the view's attribute, for example:
<TextView
android:TextSize = "10sp"
android:layout_marginTop = "10dp" />
As said in this answer, there are specific units for specific purposes.
My main question is, when applying a size programmatically (by code) in a dynamic way, what are the units applied for the size?
For example, when declaring a TextSize like this:
TextView tv = new TextView();
tv.TextSize = 10;
What are the units applied for the text size? sp? dp? px?
And most importantly, how can I change them to fit my needs?
Hi #Daniel if u programmatically generate textview as following code
TextView tv = new TextView();
tv.setTextSize(10); // Sets text in sp (Scaled Pixel).
And if you want to set text size with other unit so you can achieved by following way.
TextView tv = new TextView();
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 10); // Sets text in px (Pixel).
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); // Sets text in dip (Device Independent Pixels).
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10); // Sets text in sp (Scaled Pixel).
tv.setTextSize(TypedValue.COMPLEX_UNIT_PT, 10); // Sets text in pt (Points).
tv.setTextSize(TypedValue.COMPLEX_UNIT_IN, 10); // Sets text in in (inches).
tv.setTextSize(TypedValue.COMPLEX_UNIT_MM, 10); // Sets text in mm (millimeters).
By default Android uses "sp" for text size and "px" for view size.
For other View sizes we can set in px(pixels) but if you want customize the unit you can use custom methods
/**
* Converts dip to px.
*
* #param context - Context of calling class.
* #param dip - Value in dip to convert.
* #return - Converted px value.
*/
public static int convertDipToPixels(Context context, int dip) {
if (context == null)
return 0;
Resources resources = context.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics());
return (int) px;
}
From above method you can convert YOUR_DESIRED_UNIT in pixels and then set to view. You can replace
TypedValue.COMPLEX_UNIT_DIP
with above unit as per you use case. You can also use it vice-versa for px to dip but we cant assign to custom unit to view so that's why i am using it like this.
I hope i explained well this.
First:
I think you should avoid from set size programmatically as much as possible.
Second:
px
Pixels : corresponds to actual pixels on the screen.
dp or dip
Density-independent Pixels- : an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen
sp
Scale-independent Pixels- : this is like the dp unit, but it is also scaled by the user's font size preference
And in your third question , i think :
for example :
for a edittext you should not use constant for width like this :
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="#string/banklist_firstselectbank"
style="#style/TextAppearanceHeadline2"
android:gravity="center"/>
I think its better to use margin start and margin end like this :
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="#string/banklist_firstselectbank"
style="#style/TextAppearanceHeadline2"
android:layout_marginEnd="50dp"
android:layout_marginStart="50dp"
android:gravity="center"
/>
And use as much as possible fields like : gravity and other instead of constant number.

Android Studio constraint layout change absolute

i need to edit absolute values of ImageView:
tools:layout_editor_absoluteY="0dp"
to
tools:layout_editor_absoluteY="50dp"
but in java if I just do
ImageView img = (ImageView)findViewById(R.id.mainView);
ConstraintLayout.LayoutParams params1 = (ConstraintLayout.LayoutParams)(img.getLayoutParams());
params1.editorAbsoluteY = 50;
img.setLayoutParams(params1);
it doesn't work.
Convert your value from DP to pixels:
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
before setting the params1.editorAbsoluteY.
LayoutParams always deal with pixel values.
So you'll need to convert your DP to PX values before setting the values on the LayoutParams. There are many examples of this, a quick google should do it.
If that doesn't work, you'll need to give more information than simply saying "it doesn't work".

How to set margin for ImageView in pixels in android java?

I have a set of ImageViews whose BackgroundResource and LayoutParams will be defined in a separate xml file. The height, width, marginleft and margintop are given in pixels. The values are in respect to a 1024x600 pixel resolution screen. The code i'm using
ImageView ImgV= (ImageView)findViewById(R.id.ImgV_1);
RelativeLayout.LayoutParams the_dimens = new RelativeLayout.LayoutParams(50,50);
the_dimens.setMargins(800,50,0,0);
ImgV.setBackgroundResource(R.drawable.bulbon);
ImgV.setLayoutParams(the_dimens);
While the height and width seem to be rightly displayed in pixels, the margins are not. So how can I set the margin values to apply in pixels rather than whatever default units the below code takes.
the_dimens.setMargins(800,50,0,0);
The app is only for a 1024x600 device, so i'm not worried about resolution independent design.
Thanks.
check this
int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels
You can do in this way:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);

How to get height in pixels of LinearLayout with layout_weight

this is my first post. I am learning to code in java for android apps.
I am using a LinearLayout "variable named: ll" with a predefined layout_weight (which I want to change whenever I want in the future) and height and width set to MATCH_PARENT. I want to get the height of this LinearLayout in pixels. I fill this using java (ll.addView(variableForAnObject);).
I am trying to get its height using ll.getLayoutParams().height; but I am getting -1. Because I believe this is the constant for MATCH_PARENT. Setting the height to 0dp makes the ll invisible and gives height as 0.
Please tell me if there's a way to get its height. I think I can do this by getting screen height using DisplayMetrics and making nearly impossible calculations (for me, at least) but this will be too complex.
try with ll.getHeight() should work
if not, it's because android has not yet calculed its bounds, then:
//inside of onCreate method should work
ll.post(new Runnable() {
#Override
public void run() {
//maybe also works height = ll.getLayoutParams().height;
height = ll.getHeight();
}
});
It is -1 because its dimensions have not yet been set, whenever you set layout it takes some time to compute the actual values including height, width etc.
Use OnLayoutListener to listen when it has finished with the layout.
layout.onLayoutChange (View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//Extract values here
height = view.getHeight();
width = view.getWidth()
}
See this for more about the OnLayoutListener
Define your LinearLayout in your class and use getHeight() and getWidth(). Example:
LinearLayout yourLayout = (LinearLayout) findViewById (R.id.yourLL);
double height = yourLayout.getHeight();
double width = yourLayout.getWidth();
Hope it helps! :)
Give the id field in your layout xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/<ID>>
Use this id to get reference in java class and find height and width:
LinearLayout linearLayout= (LinearLayout) findViewById (R.id.<ID>);
double height = linearLayout.getHeight();
double width = linearLayout.getWidth();

How to set unit for Paint.setTextSize()

Is it possible to change the unit for Paint.setTextSize()? As far as I know, it's pixel but I like to set the text size in DIP for multiple screen support.
I know this topic is old and already answered but I would like to also suggest this piece of code:
int MY_DIP_VALUE = 5; //5dp
int pixel= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
MY_DIP_VALUE, getResources().getDisplayMetrics());
Convert it like this
// The gesture threshold expressed in dip
private static final float GESTURE_THRESHOLD_DIP = 16.0f;
// Convert the dips to pixels
final float scale = getContext().getResources().getDisplayMetrics().density;
mGestureThreshold = (int) (GESTURE_THRESHOLD_DIP * scale + 0.5f);
// Use mGestureThreshold as a distance in pixels
from here http://developer.android.com/guide/practices/screens_support.html#dips-pels
The accepted answer is for gestures, not setting text size. The highest voted answer (at the time of this writing) is close, but the documentation recommends using sp rather than dp because in addition to being scaled for screen densities (as dp values are), sp is also scaled according to user preferred font sizes.
From an int in code
int spSize = 17;
float scaledSizeInPixels = spSize * getResources().getDisplayMetrics().scaledDensity;
mTextPaint.setTextSize(scaledSizeInPixels);
Or alternatively
int spSize = 17;
float scaledSizeInPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spSize, getResources().getDisplayMetrics());
mTextPaint.setTextSize(scaledSizeInPixels);
From resources
Or if you have the sp or dp value in resources:
<resources>
<dimen name="fontSize">17sp</dimen>
</resources>
with
float scaledSizeInPixels = getResources().getDimensionPixelSize(R.dimen.fontSize);
mTextPaint.setTextSize(scaledSizeInPixels);
Other links
How to convert DP, PX, SP among each other, especially DP and SP?
Android: Canvas.drawText() text size on different screen resolutions
Paint.setTextSize
getDimensionPixelSize
And here is even shorter method to convert dp-s to px-els taking display metrics into account
https://developer.android.com/reference/android/content/res/Resources.html#getDimensionPixelSize(int)
If your Paint object is being used to draw text on a Canvas, you can let the Canvas handle scaling for you.
When calling Canvas.drawText() the text size is first determined by the passed in Paint object, which can be set via Paint.setTextSize(). The text size is automatically scaled by Canvas based on the canvas density, which can be found using Canvas.getDensity().
When setting the text size on a paint object that will be drawn on Canvas, work with a unit value of dp or sp and let Canvas handle the scaling for you.

Categories

Resources