定义了一个倒计时的控件,初始显示为“开始”,点击后从10开始倒计时,一直到0。可是在控件上会额外显示一个文本,如下图
额外显示的文本也会在点击开始后倒计时,找了好久一直没发现问题所在。所以请教一下各位大神。
其中自定义控件代码如下:
public class CustomView_A7 extends TextView{
private Paint paint = new Paint();
private Rect rect = new Rect();
private int mBackgroundColor= ContextCompat.getColor(getContext(), R.color.colorPrimary);
private int mTextColor = Color.WHITE;
public CustomView_A7(Context context) {
super(context);
}
public CustomView_A7(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView_A7(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画圆
paint.setColor(mBackgroundColor);
canvas.drawCircle(getWidth()/2, getWidth()/2, getWidth()/2, paint);
//画数字
paint.setColor(mTextColor);
paint.setTextSize(240);
String text = (String)this.getText();
paint.getTextBounds(text, 0, text.length(), rect);
int textWidth = rect.width();
int textHeight = rect.height();
canvas.drawText(text, getWidth()/2 - textWidth/2, getWidth()/2 + textHeight/2, paint);
}
}
Layout中只有一个自定义控件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.administrator.androidstudyapp.CustomView_A7
android:layout_width="240dp"
android:layout_height="240dp"
android:layout_gravity="center"
android:layout_margin="@dimen/activity_vertical_margin"
android:id="@+id/customView_A7"/>
</LinearLayout>
难道是Activity中的问题吗,还麻烦各位帮帮忙:
public class Point_A7_Activity extends AppCompatActivity{
private CustomView_A7 mCustomViewA7;
private int value = 10000; //10秒
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 8888:
int value = (int) msg.obj;
mCustomViewA7.setText(String.valueOf(value/1000f));
if(value > 0){
Message message = handler.obtainMessage();
message.arg1 = 1;
message.arg2 = 2;
message.what = 8888;
message.obj = value - 100;
sendMessageDelayed(message, 100);
}
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_point_a7);
mCustomViewA7 = (CustomView_A7) findViewById(R.id.customView_A7);
mCustomViewA7.setText("开始");
mCustomViewA7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message message = handler.obtainMessage();
//不要使用Message message = new Message();
message.arg1 = 1;
message.arg2 = 2;
message.what = 8888;
message.obj = value ;
handler.sendMessageDelayed(message, 100);
}
});
}
}