`

Android Tutorial #4.2: Passing custom attributes via XML resource files

阅读更多

In tutorial #4.1, I mentioned that we passed custom attributes for the text and image variables from the XML resource file to our custom class. This is a critical skill for performing true object-oriented programming and how to do it wasn’t obvious from Google’s Android API Demos.

Luckily I was pointed to the solution myself by an experienced Android programmer in Guatemala by the username of cadlg (thanks again!). If you want to see the official Google Android example though, look at Android’s APIDemos’ custom LabelView example.

So here we go. We’ll use the same code as Tutorial 4.1  to keep this simple.

Setting Up Your Custom Class’s XML Resource Files

We’ll only review the code for the TextOnlyButton as it’s identical in concept to the ImageOnlyButton.

First we’ll create a new file in /res/values called attrs.xml


<?xml version=”1.0″ encoding=”utf-8″?>
<resources>

<declare-styleable name=”TextOnlyButton”>

<attr name=”textColorNotFocused” format=”integer”/>
<attr name=”textColorFocused” format=”integer”/>

</declare-styleable>

</resources>
 

As you see, we first declared a ’styleable’ with the name of our custom Class. Two attributes were then added to contain the values of our focused & unfocused text colors. By default, attributes have values of String, but in our case, we needed integers to represent the resource id’s we’ll declare in our colors.xml file. You can also declare formats such as “boolean” & others if that suits the requirements of your own project.

Next, we declare values for these custom attributes in our layout’s XML file: tutorial4.xml


<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

xmlns:pj=”http://schemas.android.com/apk/res/com.pocketjourney.tutorials”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:padding=”10px”>

<com.pocketjourney.view.TextOnlyButton

android:id=”@+id/text_only_button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”5px”
style=”?android:attr/buttonStyleSmall”
android:text=”Text Button”
pj:textColorNotFocused=”@drawable/white”
pj:textColorFocused=”@drawable/android_orange” />

</LinearLayout> 
 

Referring to our new attributes is actually a two step process. First we declared a new namespace (in our case called ‘pj’ as short for PocketJourney) in the parent layout of our custom class:

xmlns:pj=”http://schemas.android.com/apk/res/com.pocketjourney.tutorials”

Next we specified the values of our new attributes in the XML usage of our TextOnlyButton:

pj:textColorNotFocused=”@drawable/white”
pj:textColorFocused=”@drawable/android_orange”

Now you can see why we specified our format=”integer”. Our custom attributes point to the resource id’s of colors specified in our colors.xml file.

Retrieving Custom Attributes During Class Instantiation

Since our Activity has many constructors, we delegate the attribute parsing to an init() method to keep our code clean.

int notFocusedTextColor, f ocusedTextColor;


private void init(AttributeSet attrs) {

Resources.StyledAttributes a = getContext().obtainStyledAttributes(attrs,R.styleable.TextOnlyButton );
notFocusedTextColor = a.getColor(R.styleable.TextOnlyButton_textColorNotFocused , 0xFF000000);
focusedTextColor = a.getColor(R.styleable.TextOnlyButton_textColorFocused , 0xFF000000);

}
 

By now you’ve undoubtedly seen the AttributeSet that is always passed into an Activity. Well now you get to use it. First we obtain the StyledAttributes instance by requesting just the StyledAttributes for our custom Class. Next, we call the getColor() and pass two variables: the name of the attribute we want along with a default value in case the user did not specify one.

Take note of our styled attribute’s name as it’s a combination of our custom class’s name and the attribute we specified in the attrs.xml file (e.g.TextOnlyButton_textColorNotFocused).

And That’s It

You can now readily pass your own custom attributes and keep your View variables cleanly enclosed in your XML files. You can download the source  to see for yourself. Just look at Tutorial #4.

分享到:
评论

相关推荐

    Embedfire-imx6#embed_linux_tutorial_ppt#kset:驱动的骨架1

    kset:驱动的骨架kobject的容器,体现设备驱动的层次关系kset_create_and_add()函数kset_create()函数/*注册消息发送接口

    The Busy Coders Guide to Android Development最终版2019

    Resource Sets and Configurations Material Design Basics Dealing with Threads Requesting Permissions Assets, Files, and Data Parsing Tutorial #11 - Adding Simple Content Tutorial #12 - Displaying the ...

    XML tutorial

    ### XML教程:理解XML及其对网络的影响 #### XML:一种扩展标记语言 XML,全称为“可扩展标记语言”(Extensible Markup Language),是万维网联盟(W3C)制定的一项标准,允许用户创建自定义标签。XML的出现简化...

    xml java tutorial

    在IT领域,XML(可扩展标记语言)与Java的结合为数据处理和应用程序间的数据交换提供了强大而灵活的解决方案。本文将深入探讨如何利用Java处理XML文档,通过使用Document Object Model (DOM),Simple API for XML ...

    workbook_vf

    #### Tutorial #1: 创建与列表化Visualforce Pages **步骤1:启用Visualforce开发模式** - 首先确保您的Salesforce环境已启用Visualforce开发模式。 - 这一步骤通常在设置中完成,确保您可以访问所有Visualforce...

    CommonsWare.The.Busy.Coders.Guide.to.Android.Development.Version.8.2.2017

    Android, the next-generation open mobile platform from Google and the Open Handset Alliance, is poised to become a significant player in the mobile device market. The Android platform gives developers...

    Tutorial #1 Getting started.mp4

    Tutorial #1 Getting started.mp4

    DirectX 11 Tutorials(directx11 入门教程)

    Tutorial 1: Setting up DirectX 11 with Visual Studio Tutorial 2: Creating a Framework and Window Tutorial 3: Initializing DirectX 11 Tutorial 4: Buffers, Shaders, and HLSL Tutorial 5: ...

    Tutorial #3 Geometry and texture retouching.mp4

    Tutorial #3 Geometry and texture retouching.mp4

    FLUENT TUTORIAL GUIDE

    ### 标题:FLUENT TUTORIAL GUIDE #### 描述:FLUENT TUTORIAL GUIDE #### 标签:FLUENT #### 部分内容:ANSYS FLUENT Tutorial Guide ### 知识点分析: #### 1. **ANSYS FLUENT简介** ANSYS FLUENT是一款...

    Target for ArcGIS Tutorial

    根据给定的文件信息,以下是从“Target for ArcGIS Tutorial”中提炼出的关键知识点: ### 标题:Target for ArcGIS教程 此标题表明文档旨在作为用户学习如何使用Target for ArcGIS软件的指南。Target for ArcGIS...

    OpenGL Shading Language (3rd Edition)

    Part reference, part tutorial, this book thoroughly explains the shift from fixed-functionality graphics hardware to the new era of programmable graphics hardware and the additions to the OpenGL API ...

    Tutorial #2 Georeferencing, tiling and region-of-interest.mp4

    Tutorial #2 Georeferencing, tiling and region-of-interest.mp4

    A Tutorial on JasperReports, iReport and JFreeChart

    ##### 4.2 使用JasperReports创建最终报表 接下来,使用JasperReports的API来填充`.jrxml`文件中的数据。JasperReports支持多种数据源,如数据库查询结果、XML文件等。填充完成后,可以通过JasperReports生成各种...

    XML Tutorial

    - **描述**:“XML Tutorial,XML format syntax, easy to understand.” 描述了文档内容涉及XML的基本格式和语法,并强调了易于理解的特点。 #### 关键知识点详述 1. **XML文档结构** - **XML声明**: 文档的第一...

    4.2 RNN 循环神经网络 分类 (PyTorch tutorial 神经网络 教学)

    #4.2_RNN_循环神经网络_分类_(PyTorch_tutorial_神经网络_教学)

    XMLSpyTutorial 2012 Altova xmlspy

    《深入探索XMLSpy 2012:Altova XMLSpy的全面教程》 XMLSpy是Altova公司开发的一款强大的XML编辑器和开发工具,广泛应用于XML文档的创建、编辑、转换以及验证等环节。本教程将围绕XMLSpy 2012版本,详细解析其功能...

    fragstats4.2中文教程

    ### FRAGSTATS4.2中文教程知识点概览 #### 一、FRAGSTATS简介与准备工作 **FRAGSTATS4.2**是一款专为生态学家和地理信息系统(GIS)用户设计的强大软件工具,主要用于量化和分析景观的破碎化程度。通过一系列的...

    JBoss Seam Tutorial

    org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter &lt;type-mapping&gt;Oracle9i ``` #### 步骤4:复制Oracle JDBC驱动 将Oracle JDBC驱动复制到JBOSS_HOME/server/default/lib目录下。 #### ...

Global site tag (gtag.js) - Google Analytics