Search code examples
androidcallbackandroid-custom-view

How does a custom view get data from the activity?


I have a custom View which reacts on touch event: it searches for the touched position in my Vector currenMonsters<Monster> to identify the "Monster". In the custom view I will draw the monsters.

The current<Monster> Vector and a hasmap(hashmapMonsterStandartBitmap) with the monster bitmaps are not in the custom view. They are in the activity which have set its contenview with the custom view.

How do I send the touch-event information to the activity? (I suppose by interface callbacks?)

How do I access the "currentMonster" vector which is stored in the activity from the custom view?

At the moment I have stored the currentMonster vector and hashmap and some other logic, in the view - I want to put them in the activity.

Here is some code sample (in the custom view, shorted):

@Override
  public boolean onTouchEvent(MotionEvent event) {

    // get pointer index from the event object
    int pointerIndex = event.getActionIndex();

    // get pointer ID
    int pointerId = event.getPointerId(pointerIndex);
    Log.i("touch","event.getPointerID(): "+pointerId);


    // get masked (not specific to a pointer) action
    int maskedAction = event.getActionMasked();

    switch (maskedAction) {

    //Detection of a finger touch
    case MotionEvent.ACTION_DOWN:
        totalClickt = totalClickt+1;
        fingerpointer = new PointF();
        fingerpointer.x = event.getX(0);
        fingerpointer.y = event.getY(0);
        
        for (int i=currentMonsters.size()-1; i >= 0; i--){
            if(currentMonsters.elementAt(i).getDimension().contains((int)fingerpointer.x, (int)fingerpointer.y)){
                Log.i("MonsterTouchted","MonsterTouched: index: "+i);
                attackMonster(currentMonsters.elementAt(i).getID());
            }
        }

    invalidate();

    return true;
  }
 }




 @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    
    // draw mosnters

      
    for(int i=0; i < currentMonsters.size();i++){
        if( currentMonsters.elementAt(i) != null){
            
            canvas.drawBitmap(hashmapMonsterStandartBitmap.get(currentMonsters.elementAt(i).getImagePath()),
                              currentMonsters.elementAt(i).getDimension().getX(),
                              currentMonsters.elementAt(i).getDimension().getY(),
                              mPaint); //bitmap, space left, space top, paint
            
        } else{
            Log.i("Failure","Draw monster nullpointer at index: "+i);
        }
    }
      
  }

Solution

  • You can get the context and cast it to your activity. And you can call public methods of your activity.