Search code examples
androidpixelresolutiondpisetx

Why use setX and setY?


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!


Solution

  • 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.