自定義組件實現跑馬燈效果
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>
效果圖(從右向左):