源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android自定义View控件实现刷新效果

  • 时间:2022-01-03 03:50 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android自定义View控件实现刷新效果
[b]三种得到LinearInflater的方法[/b] a. LayoutInflater inflater = getLayoutInflater(); b. LayoutInflater localinflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); c. LayoutInflater inflater = LayoutInflater.from(context); onDraw 方法绘图,invalidate刷新界面。 效果图: 点击一下换颜色 [img]http://files.jb51.net/file_images/article/201611/2016112885820323.png?2016102885846[/img] onDraw画完图后,给控件设置点击事件 ,将参数传到控件里,然后invalidate刷新 [b]1.onDraw画图,并增加changeColor方法[/b]
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++; 
} 
}
[b]2.布局[/b]
<?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>
[b]3.画图后 给控件设置点击事件 ,将参数传到控件里,然后invalidate刷新[/b]
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控件实现刷新效果,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部