自定义组件实现跑马灯效果

自定义组件实现跑马灯效果

1:组件类:
public class MyView2 extends View {
    private Mythred mythred;
    private Paint paint;
    private int rx = getWidth();//文字的x方向位置

    //自定义组件在布局中调用时执行以下方法
    public MyView2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //自定义组件在代码中调用时执行以下方法
    public MyView2(Context context) {
        super(context);
    }

    /**
     * 各条边距离左上右下的距离(left,top,right,bottom)
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint = new Paint();
        paint.setAntiAlias(true);//抗锯齿
        paint.setTextSize(30);

        canvas.drawText("自定义组件实现跑马灯效果", rx, 100, paint);
        canvas.drawRect(rx, 400, rx+100, 500, paint);

        if(mythred==null){
            mythred = new Mythred();
            mythred.start();
        }
    }
    /**
     * paint.measureText("自定义组件实现跑马灯效果")//获得文字长度
     * @author Administrator
     *
     */
    class Mythred extends Thread{
        @Override
        public void run() {
            super.run();
            int p = getMeasuredWidth();//屏幕的宽度
            while(true){
                try {
                    rx -=2;
                    postInvalidate();//更新线程,会从新调用onDraw方法
                    if(rx < 0-paint.measureText("自定义组件实现跑马灯效果")){//文字完全从屏幕消失了
                        Log.e("tag", "---------   "+rx);
                        rx = getWidth();
                    }
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2:实现类
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//调用布局
        //setContentView(new MyView2(this));//调用自定义代码

    }
}

3:布局
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <com.trkj.dept12_customer1.MyView2
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

效果图(从右向左):
这里写图片描述
这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章