Skip to content Skip to sidebar Skip to footer

Passing A Variable To A Custom View Class From Actvity

I am testing drawing audio frequency into canvas using canvas.drawLine() method. I am able to do static draw into canvas. Basically I have a test app which has two buttons START an

Solution 1:

Create Getter/Setter for currentPoint variable inside WaveForm to get value from MainActivity before calling draw as:

publicclassWaveFormextendsView {

    privatedoublecurrentPoint=50;
    publicvoidsetCurrentPoint(double currentPoint){
         this.currentPoint=currentPoint;
    }
    publicdoublegetCurrentPoint(){

       returnthis.currentPoint;
    }
    @OverrideprotectedvoidonDraw(Canvas canvas) {

        canvas.drawLine(x, 0, y, getCurrentPoint(), mLinePaint);   
        ...
    }

}

and from MainActivity set currentPoint value by calling setCurrentPoint method before calling onDraw:

for(int i=0; i<samples.length; i++) {
        currentPoint = samples[i];
        myInstance.setCurrentPoint(currentPoint);
        myInstance.draw(canvas);
        myInstance.invalidate();
    }

Solution 2:

Specify currentPoint as a static variable, and use MainActivity.currentPoint to get the value of the variable from your other class. Alternatively, just use a getter method that returns the variable.

Post a Comment for "Passing A Variable To A Custom View Class From Actvity"