Search code examples
androidandroid-layoutandroid-image

Android placing and image on a screen with a background image


I apologize for this simple question. I wrote a simple story app, using Android, but what to add some interaction to it. I thought adding some hidden images that are clickable would be fun for the young reader as they read the story. I was able to put hidden images on the screen and that worked. Now I would like to place them on the screen at particular locations. For example like a squirrel in a tree appears when you touch the branch. Is there a tutorial somewhere that shows how to do that. I would also need it to be consistent with other screen sizes, i.e. tablet, plus phones, etc.

thanks


Solution

  • Try overriding onTouch method and adding the image at the coordinates where the touch event happened.

    public boolean onTouch(View v, MotionEvent event) {
    
      if (event.getAction() == MotionEvent.ACTION_DOWN){
          int x = (int) event.getX() ;
          int y = (int) event.getY();
          RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);; //Assuming you use a RelativeLayout
          ImageView iv=new ImageView(getApplicationContext());
          lp.setMargins(x,y,0,0);
          iv.setLayoutParams(lp);
          iv.setImageDrawable(getResources().getDrawable(/*id of your image*/));
          ((ViewGroup)v).addView(iv);
      }
    

    And make sure that the Layout you override onTouch for is RelativeLayout, filling the entire screen

    You can also look at the following project on Github, it is somewhat related to what you are looking for. enter link description here