I have a code on ICS for tablets. I want to add a Imageview dynamicly to a fragment. The fragment already contains preferencelist. The code for adding the view dynamically
Try setting gravity to Gravity.TOP | Gravity.LEFT
I m working exatly on the same code taken from the old Google Music open souce project.
Like you I guess, I had a TouchInterceptor
in a fragment. My problem was that the fragment does not take all the screen widht, it has an other fragment on its left.
I tried a lot using mWindowParams.gravity
to be able to specify an absolute x,y but I couldn't find a solution. Eventually I solved it with mWindowParams.horizontalMargin
.
Here is the code I came up with:
private int getAbsoluteLeft(){
ViewGroup parent;
View child = this;
int left_absolute_position = 0;
try{
while( (parent = (ViewGroup) child.getParent()) != null) {
left_absolute_position += child.getLeft();
child = parent;
}
}catch(ClassCastException e){
}
return left_absolute_position;
}
private void startDragging(Bitmap bm, int x, int y) {
stopDragging();
//build the view
Context context = getContext();
ImageView v = new ImageView(context);
//int backGroundColor = context.getResources().getColor(R.color.dragndrop_background);
//v.setBackgroundColor(backGroundColor);
//v.setBackgroundResource(R.drawable.playlist_tile_drag);
v.setPadding(0, 0, 0, 0);
v.setImageBitmap(bm);
mDragBitmap = bm;
mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
//Build Params
mWindowParams = new WindowManager.LayoutParams();
mWindowParams.gravity = Gravity.TOP | Gravity.LEFT;
mWindowParams.x = ( x - mDragPointX + mXOffset );
mWindowParams.y = ( y - mDragPointY + mYOffset );
DisplayMetrics metrics = new DisplayMetrics();
mWindowManager.getDefaultDisplay().getMetrics(metrics);
mWindowParams.horizontalMargin = (float)getAbsoluteLeft() / (float)metrics.widthPixels;
mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
mWindowParams.format = PixelFormat.TRANSLUCENT;
mWindowParams.windowAnimations = 0;
mWindowManager.addView(v, mWindowParams);
mDragView = v;
}
The part I added is:
DisplayMetrics metrics = new DisplayMetrics();
mWindowManager.getDefaultDisplay().getMetrics(metrics);
mWindowParams.horizontalMargin = (float)getAbsoluteLeft() / (float)metrics.widthPixels;
This parameter mWindowParams.horizontalMargin
specify the margin of the window from the specified gravity side (Gravity.Left
) as a % € [0,1].
So with getAbsoluteLeft()
I go up to the View tree to get the absolute distance of the list from the left side.
Dividing it by the window's width, you get percent of margin you need.