Search code examples
androidviewandroid-canvasandroid-buttonviewgroup

Using ViewGroup and View on Android draw and make buttons using canvas


I'm trying to make my own custom view, currently all it does is draw an image on a specific x and y coordinate and then draws the similar images repeatedly on different locations.

I want to be able to create a button on each instance of the image that is drawn. if one image is clicked it will have cause something different to happen depending on which image is chosen.

How can I implement this?

would I have to create a different view for each image/button combination and then set an onClick event?


Let me try to be a little more clear I'm trying to make a map using hexagon (different types of terrains for different players) I've figured out how to get them to draw (see here - they will have a border to show what terrain is owned by whom)

I just made a custom view class and had the hexagons drawn using a Canvas; however, I'm not sure how to be able to make the hexagons into buttons so that I can differentiate between which hexagon was chosen and how it should react to the opponents spot.

I was thinking of making a ViewGroup called Terrain to contain the Nodes(hexagons) that belong to the player and have a group of Node Views that only draw the hexagon where it should be located.

the question is can i make each node or the entire viewGroup into a button (or do an onTouch ) if a certain hexagon is pressed?


Solution

  • Thanks for your help!

    I figured out what I needed to do. I have a NodeView class and in my GameActivity class, I'm using a relative layout and setting the layout parameters of where I wanted things positioned

        RelativeLayout rl = new RelativeLayout(this);
    
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(95,95);
        params.leftMargin = 10;
        params.topMargin = 10;
    
    
        params = new RelativeLayout.LayoutParams(95,95);
        params.leftMargin = 10+95*x;
        params.topMargin = 81+(71*y);
        rl.addView(new NodeView (this,0,0,1,1), params);
    

    This helped me add things where I needed them and now all I'm trying to figure out how to scroll around the territories on both the x and y axis (I tried ScrollView but that only allows me to scroll on the y-axis, I'm looking into it though)