Search code examples
androidbitmapandroid-linearlayoutdrawmove

How to draw and move bitmap inside of linearlayout when this was created


I wish my bitmap moved when I click on it and I move around the board. The code I am using so far is this:

LinearLayout ll = (LinearLayout) findViewById(R.id.table);
ll.setWillNotDraw(false);

ll.setOnTouchListener(new View.OnTouchListener() { 
 @SuppressLint("ClickableViewAccessibility") @Override
                public boolean onTouch(View arg0, MotionEvent event) {
                    //gesture detector to detect swipe.
                    int x = (int) event.getX();
                    int y = (int) event.getY();

                    switch(event.getAction()){
                      case MotionEvent.ACTION_DOWN:
                      break;

                      case MotionEvent.ACTION_MOVE:
                        X=x; Y=y;
                      break;

                      case MotionEvent.ACTION_UP:
                      break;
                    }
                    return true;
                }
            });

   ll.setBackground(new BitmapDrawable(getResources(), bg)
            {

                @Override
                public void draw(Canvas canvas) {
                   canvas.drawBitmap(bitmap,X,Y, null);
                }
            });

In the case MOVE, i put the new X and Y of the new position of the bitmap. I thought that draw() was drawing all time. Inside of draw(), I paint more bitmaps, but they are fixed.

What i can do? I accept change of the struct, but I prefer to continue this code. Thank you.


Solution

  • Try to create a class extends View , override the onDraw(Canvas canvas), then use matrix.postTranslate(x, y) and canvas.drawbBitamp(bitmap, matrix, null) instead.

    And when you need to refresh the view, use invalidate() method