简体   繁体   中英

Created this simple code to draw circle in android and it shows nothing on emulator

I created this simple code in android and it shows nothing on emulator it should show a circle. Do I have to edit something in the xml file also?

Here my main activity

public class MainActivity extends AppCompatActivity {
    Circlexy ourview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ourview = new Circlexy(this);
        setContentView(ourview);
    }
}

And this is my Circlexy class:

public class Circlexy extends View {
    Bitmap ball;
    public Circlexy (Context context){
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint= new Paint();
        paint.setColor(Color.BLUE);
        canvas.drawCircle(canvas.getWidth()/2,canvas.getHeight()/2,100,paint);
    }
}

You are not setting a layout to your Activity and hence any change you do , be in programmatic or in xml , you would not be able to see it.

The setContentView() Method is used to set the layout (xml) file to the present activity but you're passing your circle View to it, You should set the content as the xml file using the "R" reference. Something like :

setContentView(R.layout.activity_main);

Where, your activity xml is named activity_main.xml

Also , on another Note , You Should Also Update Your Circlexy Class to include other constructors for good practice.

public class Circlexy extends View {


public Circlexy(Context context) {
    super(context);
}

public Circlexy(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public Circlexy(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint= new Paint();
    paint.setColor(Color.BLUE);
    canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 100, paint);
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM