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屬性,對應(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ù)自定義的命名空間和我們在attrs中設(shè)置的屬性,自定義屬性值
gu:rect_color="#cc99cc" />
</LinearLayout>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android自定義控件實(shí)現(xiàn)萬能的對話框
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)萬能對話框的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
Android中顯示GIF動(dòng)畫的實(shí)現(xiàn)代碼
這篇文章主要介紹了Android中顯示GIF動(dòng)畫的實(shí)現(xiàn)代碼,較為詳細(xì)的分析了Android調(diào)用GIF動(dòng)畫所涉及的頁面布局及功能實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10
Android Activity Results API代替onActivityResul
說到onActivityResult,我們已經(jīng)非常熟悉來,通過在A activity啟動(dòng)B activity并且傳入數(shù)據(jù)到B中,然后在A中通過onActivityResult來接收B中返回的數(shù)據(jù)。在最新的activity-ktx的beta版本中,谷歌已經(jīng)廢棄了onActivityResult2022-09-09
Android嵌套滾動(dòng)的傳統(tǒng)方法與思路
Android嵌套滾動(dòng)是在開發(fā)中經(jīng)常遇到的一個(gè)需求,這篇文章主要介紹了Android嵌套滾動(dòng)的傳統(tǒng)方法與思路的相關(guān)資料,對各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Android中RecyclerView 滑動(dòng)時(shí)圖片加載的優(yōu)化
本篇文章主要介紹了Android中RecyclerView 滑動(dòng)時(shí)圖片加載的優(yōu)化,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04

