public class MainActivity extends AppCompatActivity { private ToListItemView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (ToListItemView) findViewById(R.id.tv); tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Random random=new Random(); int i = random.nextInt(10000); if(i>1000){ tv.setText(i+""); }else{ } } }); } }
//自定义类
public class ToListItemView extends TextView { public ToListItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public ToListItemView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public ToListItemView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub Paint mPaint1 = new Paint(); mPaint1.setColor(getResources().getColor(android.R.color.holo_blue_light)); mPaint1.setStyle(Paint.Style.FILL); Paint mPaint2 = new Paint(); mPaint2.setColor(Color.YELLOW); mPaint2.setStyle(Paint.Style.FILL); //绘制外层矩形 canvas.drawRect(0, 0, getMeasuredWidth(),getMeasuredHeight(), mPaint1); //绘制内层矩形 canvas.drawRect(10, 10, getMeasuredWidth()-10, getMeasuredHeight()-10, mPaint2); canvas.save(); //绘制文字前平移10像素 canvas.translate(10, 0); super.onDraw(canvas); canvas.restore(); } }
//布局
<com.bawei.ceshi.ToListItemView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/tv" android:textColor="#f00" android:background="#ff0" android:text="1202" />