package com.jiyun.dell.myview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { private LinearLayout linear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //绑定控件 linear = (LinearLayout) findViewById(R.id.ll); //创建画画的类 MyView myview=new MyView(MainActivity.this); //进行配置 myview.invalidate(); // 把画画的这个类(View)添加到布局中 linear.addView(myview); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/ll" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.jiyun.dell.myview.MainActivity"> </LinearLayout>
package com.jiyun.dell.myview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; /** * Created by DELL zhanghuirong on 2017/8/14. */ public class MyView extends View { //这是一个参数的构造方法 public MyView(Context context) { super(context); } @Override//重写画圆的方法 protected void onDraw(Canvas canvas) { super.onDraw(canvas); //创建画笔工具 Paint paint=new Paint(); //给画笔设置颜色 paint.setColor(Color.GREEN); // 在画布上画圆 括号里的参数,前两个是偏移量也就是离圆心的距离,50是半径,painit是画笔 canvas.drawCircle(100,100,50,paint); } }