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".
Related
I have multiple layouts. By all I have hight=0 and and weigth=something. But now I want to add a layout that will allways be 60px. All works perfectly but now I need to know how much weight is 60px because I neet it for something else I am working on. So is it possible to get screen dimensions in dp. NOTE: I need to know the dp for each section. image
How exact can this be?
you can get the screen width and height like this:
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
then you just divide the height you get by the number of layouts you want to display
EDIT: another option would be(if you know the number of layouts at compile time) to give each layout the same layout_weight value f.e. layout_weight=1
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);
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)
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();
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.