How to make a group of clickable graphical object?
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
publi开发者_StackOverflow中文版c 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 :)
It should be as easy as making your clas
CustomDrawableView extends View implements OnClickListener {
// all your code here
public void onClick(View v) {
// your callback function here
}
}
Take a look at one example I wrote some time ago in this answer: Android onClick method doesn't work on a custom view
精彩评论