Reputation: 320
OK now I know that the question seems to has an obvious answer, but really what is wrong with setX and setY functions and why won't they just work as they supposed to be. I'm trying to move views dynamically while the app is running to certain positions.They worked fine on my testing device with mdp but everything changes when I use device with different density value.The Y axis always off by a constant value, and no it is not a padding or margin issue I even tried to divide it by context.getResources().getDisplayMetrics().density;
to take the densities differences into consideration but it didn't work either.
finally I used the answer in this post and it worked but I still have problems with other densities devices.
This is what it suggested:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
//WRAP_CONTENT param can be FILL_PARENT
params.leftMargin = 206; //XCOORD
params.topMargin = 206; //YCOORD
childView.setLayoutParams(params);
so can someone tell me why this is happening? setX and setY supposed to make it easier...right? please if I'm just speaking none sense and you could solve this for me I'd appreciate it a lot, I latterly tried everything!
Upvotes: 1
Views: 690
Reputation: 320
So after much much research I finally solved the issue. What i had was a GridView and couple of LinearLayout all wrapped up inside a relativeLayout and I used getLocationOnScreen() to get the coordinates of a cell in the gridView so I could put view over it, for some reason there was always a fixed value difference in Y axis that varies in different device densities, finally I put the GridView inside a relativeLayout alone so it is the only child and used getX() getY() which get the coordinates inside the direct parent of a view, the result was just what I wanted and I didn't even have to count for different density screens. Hope this will help someone who may encounter the same issue.
Upvotes: 1
Reputation: 241
This explains how to convert dp to px programmatically
Long story short: Every numerical value you set on View objects that in xml can be expressed as a dp value, are expressed as raw pixels when you set them programmatically. The following code snippet tells you how to convert from dp to raw pixels:
// The gesture threshold expressed in dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);
// Use mGestureThreshold as a distance in pixels...
Hope that helps!
Upvotes: 3