Search code examples
androidinvalidation

Call onDraw manually from popup in activity


I do not get it. I have tried many suggestions like

this.findViewById(android.R.id.content).postInvalidate();
getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
getWindow().getDecorView().findViewById(android.R.id.content).postInvalidate();
    etc

from stackoverflow but it still does not work.

Problem: Activity --> setContentView(new drawView(this,controller)); Activity --> PopupWindow

How could i call onDraw in my DrawView from my PopupWindow?

Edit:

public class GraphActivity extends Activity {
   ... 
   setContentView(new DrawView(this,controller));
   ...
   public void showTransitionTable() {
      ...
      View popupview = getLayoutInflater().inflate(R.layout.sim_pop, sim,false);
      ...
      btnClock.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
      //call here DrawView onDraw
      }
}


public class DrawView extends View {
    protected void onDraw(Canvas canvas) {
    ...
    }
}

Solution

  • This is an example of what I mean ...

    public class MainActivity extends Activity {
    
    private class DrawView extends View {
    
        private List<Point> pointList;
        private Paint paint = new Paint();
        private Random random = new Random();
        private Paint background = new Paint();
    
        public DrawView(Context context) {
            super(context);
            background.setColor(Color.BLACK);
        }
    
        @Override
        public void onDraw(Canvas canvas) {
            if(pointList==null) return;
            canvas.drawPaint(background);
            for (Point p : pointList) {
                paint.setColor(Color.argb(255, random.nextInt(255), random.nextInt(255), random.nextInt(255)));
                canvas.drawCircle(p.x, p.y, 10+random.nextInt(10), paint);
            }
        }
    
        public void setPoints(List<Point> pointList) {
            this.pointList = pointList;
        }
    
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        final DrawView view = new DrawView(this);
        setContentView(view);
    
        final List<Point> pointList = new ArrayList<Point>();
        view.setPoints(pointList);
    
        final Random random = new Random();
    
        new AlertDialog.Builder(this).setMessage("Click OK for more circles").setPositiveButton("OK", new OnClickListener() {
    
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for(int i= 0; i<10; i++) pointList.add(new Point(random.nextInt(view.getWidth()), random.nextInt(view.getHeight())));
                view.invalidate();
            }
        }).create().show();
    
    }
    
    }