实现结果
步骤:
1、自定义类继承TextView,重写Ondraw()方法
2、主方法不做更改
3、布局文件添加tv。条目为自定义类的路径
代码如下:
自定义类:
public class Ruler extends TextView {
public Ruler(Context context) {
super(context);
init();
}
public Ruler(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public Ruler(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
// 初始化,设置控件的位置
private void init() {
setGravity(Gravity.BOTTOM);
}
/**
* 实现该方法,“画出”自己想实现的画, 该方法无须手动调用,系统绘制该控件时,会自行调用该方法
*
* @Override
*/
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
int w = getWidth() / 10;
float top = 1;
for (int i = 0; i < 10; i++) {
canvas.drawRect(i * w, top, i * w + w, top * w, paint);
}
canvas.drawText("hehe", 20, 20, paint);
}
}
2、主方法
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
3、布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.days27selfview03.Ruler
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#00ccff"
android:text="@string/btnText" />
<com.days27selfview03.Ruler
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#ff00cc"
android:text="@string/btnText" />
<com.days27selfview03.Ruler
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#00ffcc"
android:text="@string/btnText" />
<com.days27selfview03.Ruler
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#ffccff"
android:text="@string/btnText" />
</LinearLayout>
来源:oschina
链接:https://my.oschina.net/u/2728095/blog/680732