Monday, April 16, 2012

Draw clickable rectangles and I do not know how set params before onDraw method

I am trying to make clickable rectangles. I've looked around and I created quite good code :)



I create constructor of my own rectangle class, then i set some values of it.
However, onDraw method looks like creates and draw rectangle but without constructor's new variables' values.
What do I do wrong?



This is default MyActivity class:



ll = (LinearLayout)findViewById(R.id.linearlayout);
List<MiniRectangle> miniRectangleList = new ArrayList<MiniRectangle>();

for(int i=0;i<8;i++)
{
int numberRandom = r.nextInt(3);

MiniRectangle miniRectangle = new MiniRectangle(this);
miniRectangle.set_color(colors.get(numberRandom));
miniRectangle.set_size(50);
miniRectangle.set_id_color(numberRandom);
miniRectangle.set_number(i);

ll.addView(miniRectangle);

miniRectangleList.add(miniRectangle);
}

setContentView(ll);


This is my own rectangle class



public class MiniRectangle extends View implements View.OnClickListener {

Context context;
int _size;
int _color;
int _id_color;
int _number;

public MiniRectangle(Context context) {
super(context);
this.context = context;
setOnClickListener(this);
}

@Override
public void onClick(View view) {
System.out.println(get_number());
Toast.makeText(context, get_number(), Toast.LENGTH_SHORT).show();
}

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

Paint paint = new Paint();
paint.setColor(get_color());
paint.setStrokeWidth(1);

int kleft = (get_number() % 8) * get_size();
int kright = kleft + get_size() - 2;

int ktop = 1 * get_size();
int kbottom = ktop + get_size() - 2;

canvas.drawRect(kleft, ktop, kright, kbottom, paint);
}
}


I can say that after run project I get only one rectangle. No wonder if every rectangle has the same position. Please Help.





No comments:

Post a Comment