Android自定义View控件实现刷新效果
程序员文章站
2024-02-29 18:06:16
三种得到linearinflater的方法
a. layoutinflater inflater = getlayoutinflater();
b. layoutinf...
三种得到linearinflater的方法
a. layoutinflater inflater = getlayoutinflater();
b. layoutinflater localinflater =
(layoutinflater)context.getsystemservice
(context.layout_inflater_service);
c. layoutinflater inflater = layoutinflater.from(context);
ondraw 方法绘图,invalidate刷新界面。
效果图:
点击一下换颜色
ondraw画完图后,给控件设置点击事件 ,将参数传到控件里,然后invalidate刷新
1.ondraw画图,并增加changecolor方法
public class cusview3 extends view { private int color = 0; public cusview3(context context, attributeset attrs) { super(context, attrs); } @override protected void ondraw(canvas canvas) { super.ondraw(canvas); paint mpaint = new paint(); if (color > 2) { color = 0; } switch (color) { case 0: mpaint.setcolor(color.green); break; case 1: mpaint.setcolor(color.red); break; case 2: mpaint.setcolor(color.blue); break; default: break; } mpaint.setstyle(style.fill); mpaint.settextsize(35.0f); canvas.drawtext("点击我刷新", 10, 60, mpaint); } public void changecolor() { //为了让外面调用 color++; } }
2.布局
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <xue.test.cusview3 android:id="@+id/cusview3" android:layout_width="wrap_content" android:layout_height="wrap_content" > </xue.test.cusview3> </linearlayout>
3.画图后 给控件设置点击事件 ,将参数传到控件里,然后invalidate刷新
public class testcustomviewactivity extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); view3 = (cusview3) findviewbyid(r.id.cusview3); // 点击事件 view3.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { message message = new message(); message.what = 1; myhandler.sendmessage(message); } }); } handler myhandler = new handler() { // 接收到消息后处理 public void handlemessage(message msg) { switch (msg.what) { case 1: // 调用方法 view3.changecolor(); // 刷新方法 view3.invalidate(); break; } super.handlemessage(msg); } }; private cusview3 view3; }
至于自定义控件占整屏的问题,可能需要用layoutparams
以上所述是小编给大家介绍的android自定义view控件实现刷新效果,希望对大家有所帮助
下一篇: 计算机基础