0

my question is how can I make a set of clickable images on Android.

I can make one clickable sphere by using ShapeDrawable, however I want to make more than one at once and still be able to get clicks in all of them.

Moreover I want to position them on screen at my will, instead of auto positioned as with layouts.

The number of spheres can change as can the places.

This is the code I use to make one:

Main.java

package com.teste;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layout = new LinearLayout(this);

        CustomDrawableView mCustomDrawableView = new CustomDrawableView(this, 100, 100, 50, 50, 0xff74AC23);
        CustomDrawableView mCustomDrawableView2 = new CustomDrawableView(this, 10, 10, 50, 50, 0xffffffff);

        mCustomDrawableView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(), "Clicked green ball", Toast.LENGTH_SHORT).show();  
            }
        });

        mCustomDrawableView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(), "Clicked white ball", Toast.LENGTH_SHORT).show();  
            }
        });

        layout.addView(mCustomDrawableView);
        layout.addView(mCustomDrawableView2);
        setContentView(layout);

    }
}

CustomDrawableView.java

package com.teste;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class CustomDrawableView extends View {
    private ShapeDrawable mDrawable;

    public CustomDrawableView(Context context, int i, int j, int k, int l, int m) {
        super(context);

        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        super.setLayoutParams(params);

        mDrawable = new ShapeDrawable(new OvalShape());
        mDrawable.getPaint().setColor(m);
        mDrawable.setBounds(i, j, i + k, j + l);
    }

    protected void onDraw(Canvas canvas) {
        mDrawable.draw(canvas);
    }
}

Hope you can help :)

4

1 回答 1

0

它应该像制作你的班级一样简单

CustomDrawableView extends View implements OnClickListener {
    // all your code here

    public void onClick(View v) {
          // your callback function here
    }
}

看看我前段时间在这个答案中写的一个例子:Android onClick method doesn't work on a custom view

于 2011-05-10T22:13:15.537 回答