andriod 继承view定义自己的形状

andriod 继承view定义自己的形状

这里主要讲通过继承view定义自己的一个形状,并在Activity中使用和在布局文件中使用

看一下运行的效:

https://img-my.csdn.net/uploads/201304/14/1365908374_1562.png

黄色的正方形是一个自定义的view,一下是实现的代码,黄色正方形是在xml中定义的,其中有一部分注释掉了,那是通过直接在Activity中new 出来的,你可以在两种方法之间转换:

主要Activity:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// MyRectangle rec = new MyRectangle(this);
// setContentView(rec);
setContentView(R.layout.activity_main);
}
}

主要布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   <com.example.defineviewrotateanimation.MyRectangle
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">      
   </com.example.defineviewrotateanimation.MyRectangle>
</RelativeLayout>

正方形view的类:

public class MyRectangle extends View{
Paint paint = new Paint();

public MyRectangle(Context context) {    //此构造函数可以直接new出来,在Activity中使用
super(context);
paint.setColor(Color.YELLOW);
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.FILL);   //设置绘制的封闭图形填充
}

public MyRectangle(Context context, AttributeSet attrs) {   //此构造函数用于在xml中引用
super(context, attrs);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.FILL);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Path p = new Path();
p.moveTo(0, 0);        //绘制矩形的起点
p.lineTo(100, 0);      //从点(0,0)到点(100,0)绘制一条线
p.lineTo(100, 100);     //从点(100,0)到点(100,100)绘制一条线
p.lineTo(0, 100);
p.lineTo(0, 0);
canvas.drawPath(p, paint);
}
}

注意:public MyRectangle(Context context, AttributeSet attrs) 此构造函数不能少,否则在xml中引用将会报错

以下是Demo下载地址:http://download.csdn.net/download/lyhdream/5256194

推荐阅读:http://blog.csdn.net/lingxiang0614/article/details/6817065




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值