今天小編跟大家分享一篇關(guān)于Android中View的使用深入解析,感興趣的朋友跟小編一起來了解一下吧!
在項(xiàng)目開發(fā)中,可能系統(tǒng)自帶的一些widget不能滿足我們的需求,這時(shí)就需要自定義View。
通過查看系統(tǒng)中的常用widget如Button,TextView,EditText,他們都繼承自View,所以我們?cè)诶^承自定義View的時(shí)候也自然的需要繼承View。
1、首先新建一個(gè)類LView繼承自View
復(fù)制代碼 代碼如下:
public class LView extends View {
private Paint paint;
public LView(Context context) {
super(context);
}
public LView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint = new Paint();// new一個(gè)畫筆
paint.setColor(Color.RED);// 設(shè)置畫筆顏色
paint.setStyle(Style.FILL);// 設(shè)置畫筆填充
canvas.drawCircle(50, 50, 40, paint);// 用畫筆在畫布上添加一個(gè)圓,不只可以添加圓,還可以添加矩形等!
paint.setColor(Color.YELLOW);// 設(shè)置畫筆顏色
canvas.drawText("LView", 50, 50, paint);// 用畫筆在畫布上添加文字,中間兩個(gè)參數(shù)對(duì)應(yīng)的是坐標(biāo)。
}
}
2、在layout文件中進(jìn)行配置
復(fù)制代碼 代碼如下:
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
運(yùn)行程序,可以看到如下畫面:

以上就是對(duì)Android中View使用的一個(gè)大致介紹,如果你想知道得更多,更多相關(guān)內(nèi)容請(qǐng)繼續(xù)關(guān)注武林技術(shù)頻道。
新聞熱點(diǎn)
疑難解答
圖片精選