//布局文件
<com.bw.u.liangweihangdiyizhouer.MyView android:id="@+id/MyTextView" android:layout_width="600dp" android:layout_height="600dp" android:layout_centerInParent="true" />//代码
package com.bw.u.liangweihangdiyizhouer; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private boolean flag=true; private MyView myView; private int count=0; private ArrayList<String> list=new ArrayList<>(); private Handler handler=new Handler(){ public void handleMessage(Message msg) { if (msg.what==0){ myView.setText(list.get(count)); myView.setTextSize(50); myView.setBackgroundColor(Color.parseColor(list.get(count))); if (count<list.size()-1){ count++; }else { count=0; } handler.sendEmptyMessageDelayed(0, 2000); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myView = (MyView) findViewById(R.id.MyTextView); list.add("#6187c5"); list.add("#00cc00"); list.add("#ffffff"); list.add("#666cc9"); list.add("#f00000"); list.add("#00ff00"); //从元素的第一个开始 myView.setText(list.get(count)); myView.setTextSize(50); myView.setBackgroundColor(Color.parseColor(list.get(count))); if (count<list.size()-1){ count++; }else { count=0; } handler.sendEmptyMessageDelayed(0, 2000); myView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (flag){ flag=false; Toast.makeText(MainActivity.this,"关闭两秒改变事件",Toast.LENGTH_SHORT).show(); handler.removeMessages(0); }else { flag=true; count=0; Toast.makeText(MainActivity.this,"开启两秒改变事件",Toast.LENGTH_SHORT).show(); handler.sendEmptyMessageDelayed(0,2000); } } }); } }//MyView代码自定义控件
package com.bw.u.liangweihangdiyizhouer; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; public class MyView extends TextView{ private Paint mPaint; public MyView(Context context) { this(context,null); } public MyView(Context context, AttributeSet attrs) { this(context, attrs,R.style.AppTheme); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint=new Paint(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(heightMeasureSpec,widthMeasureSpec); } }