Android如何自定義視圖屬性
本文實(shí)例為大家介紹了Android自定義視圖屬性的方法,供大家參考,具體內(nèi)容如下
1. 自定義一個(gè)自己的視圖類繼承自View
public class MyView extends View
{
public MyView(Context context, AttributeSet attrs)
{
super(context, attrs);
//獲取到自定義的屬性
TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MyView);
int color=ta.getColor(R.styleable.MyView_rect_color, 0xffff0000);
setBackgroundColor(color);
//必須手動(dòng)回收ta
ta.recycle();
}
public MyView(Context context)
{
super(context);
}
}
2. 在res/values目錄中新建一個(gè)attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
//定義一個(gè)declare-styleable標(biāo)簽,在里面設(shè)置attr屬性
<declare-styleable name="MyView">
<attr name="rect_color" format="color"/>
</declare-styleable>
</resources>
一個(gè)attr屬性,對(duì)應(yīng)了一個(gè)視圖屬性
3.最后看布局文件中如何利用我們創(chuàng)建的自定義視圖并設(shè)置其屬性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
//自定義一個(gè)MyView的命名空間
xmlns:gu="http://schemas.android.com/apk/res/com.gu.myrect"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.gu.myrect.MyView
android:layout_width="100dp"
android:layout_height="100dp"
//根據(jù)自定義的命名空間和我們?cè)赼ttrs中設(shè)置的屬性,自定義屬性值
gu:rect_color="#cc99cc" />
</LinearLayout>
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android?Flutter實(shí)現(xiàn)在多端運(yùn)行的掃雷游戲
當(dāng)我們回憶起小時(shí)候的經(jīng)典電腦游戲,掃雷一定是其中之一。本文將通過Flutter實(shí)現(xiàn)一個(gè)能在多端運(yùn)行的掃雷游戲,感興趣的可以了解一下2023-03-03
Android?Flutter控件封裝之視頻進(jìn)度條的實(shí)現(xiàn)
這篇文章主要來和大家分享一個(gè)很簡單的控制器封裝案例,包含了基本的播放暫停,全屏和退出全屏,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-06-06
ijkPlayer播放器的全自動(dòng)編譯腳本及最終編譯包
這篇文章主要介紹了ijkPlayer播放器的全自動(dòng)編譯腳本及最終編譯包,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Cocos2d-x入門教程(詳細(xì)的實(shí)例和講解)
這篇文章主要介紹了Cocos2d-x入門教程,包括詳細(xì)的實(shí)例、講解以及實(shí)現(xiàn)過程,需要的朋友可以參考下2014-04-04
Android RecyclerView 復(fù)用錯(cuò)亂通用解法詳解
本篇文章主要介紹了Android RecyclerView 復(fù)用錯(cuò)亂通用解法詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
Android實(shí)現(xiàn)多個(gè)連續(xù)帶數(shù)字圓圈效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)多個(gè)連續(xù)帶數(shù)字圓圈效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Android媒體通知欄多系統(tǒng)適配實(shí)例講解
對(duì)于Android來說其中一項(xiàng)很方便的操作便是下拉菜單,下拉菜單欄可以快捷打開某項(xiàng)設(shè)置,這篇文章主要給大家介紹了關(guān)于Android通知欄增加快捷開關(guān)的功能實(shí)現(xiàn),需要的朋友可以參考下2023-04-04
android操作SQLite增刪改減實(shí)現(xiàn)代碼
android操作SQLite增刪改減實(shí)現(xiàn)代碼,學(xué)習(xí)android的朋友可以參考下。2010-11-11

