In the application, when you click on one of the two buttons, a point of the corresponding color (red or green) with random coordinates should be drawn in the view (widget). I did everything as in the example. However, view does not respond to button presses. There was also the same example, but with a model listener, who also for some reason does not work for me.
Activity:
import ru.srg.app.view.Widget; import ru.srg.app.model.DotList; public class MainActivity extends Activity { private final Random rand = new Random(); Widget dotView; final DotList dotList = new DotList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); dotView = new Widget(this, dotList); ((LinearLayout)findViewById(R.id.LinearLayout)).addView(dotView, 0); ((Button) findViewById(R.id.redButton)).setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ makeDot(dotList, dotView, Color.RED); dotView.invalidate(); } }); ((Button) findViewById(R.id.grnButton)).setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ makeDot(dotList, dotView, Color.GREEN); dotView.invalidate(); } }); } public void makeDot(DotList dotList, Widget view, int color){ dotList.addDot(rand.nextInt(900), rand.nextInt(1200), color, rand.nextInt(15)); } } Sheet:
public class DotList { public ArrayList<Model> dots = new ArrayList<Model>(); public void addDot(int x, int y, int color, int size){ dots.add(new Model(x, y, color, size)); } } An object:
public class Model { int x, y; int color; int size; public Model(int x, int y, int size, int color){ this.x = x; this.y = y; this.color = color; this.size = size; } public int getX(){ return x; } public int getY(){ return y; } public int getColor(){ return color; } public int getSize(){ return size; } } View:
public class Widget extends View { private DotList dotList = new DotList(); public Widget(Context context, DotList dotList){ super(context); this.dotList = dotList; setMinimumWidth(900); setMinimumHeight(1200); setFocusable(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight()); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); canvas.drawRect(0, 0, getWidth()-1, getHeight()-1, paint); paint.setStyle(Paint.Style.FILL); for(Model m : dotList.dots){ paint.setColor(m.getColor()); canvas.drawCircle(m.getX(), m.getY(), m.getSize(), paint); } } }