Android Custom XML Attributes

Android Custom XML Attributes

12/09/12 by Robert Hewitt

When writing code the goal is always to write little and make what you do write in reusable components. Android has always had the ability to parse the XML attributes defined when constructing a view but little used is the ability for custom attributes to be applied.
* See step 4 for adding custom attributes to library projects

Example situation

Let’s say we want to extend the functionality of an EditText to have a range applied so there are bounds to the input. This could be used for limited text entry when entering information into a database.

To add one of these such views through XML would look something like this...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <com.kotikan.blogposts.views.RangeEditText
        android:id="@+id/range_edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, MyActivity"
        />

</LinearLayout>

Then in code we would have to find the view and call through to other set up methods to complete the state loading of this RangeEditText as follows...

final RangeEditText rangeEditText = (RangeEditText) findViewById(R.id.range_edit);
rangeEditText.setMaxCharsAllowed(15);
rangeEditText.setMinCharsAllowed(7);

This is wasteful due to the constructor of this view already being called through the XML inflation phase and now having to load yet more state into this view through additional android lifecycle hooks.
Here is a step by step guide to achieving the same result through XML definition.

Step 1 - attrs.xml

Firstly we need to declare the styleable attributes so we can use them in XML markup. Create a file called ‘attrs.xml’ inside [projectRoot]/res/values/ and add the following -

<resources>
    <declare-styleable name="RangeEditText">
        <attr name="charInputMinimum" format="integer"/>
        <attr name="charInputMaximum" format="integer"/>
    </declare-styleable>
</resources>

Step 2 - Updating RangeEditText

We now need to update our class to parse these attributes. There are two constructors for a View that take AttributeSet therefore it’s often convenient to telescope the constructors for easier code maintenance.

e.g.

public class RangeEditText extends EditText {

    private int charsAllowedMinimum;
    private int charsAllowedMaximum;

    public RangeEditText(Context context) { this(context, null); }
    public RangeEditText(Context context, AttributeSet attrs) { this(context, attrs, 0); }
    public RangeEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        loadStateFromAttrs(attrs);
        /* other code */
    }
    private void loadStateFromAttrs(AttributeSet attributeSet) {
        if (attributeSet == null) {
            return; // quick exit
        }

        TypedArray a = null;
        try {
            a = getContext().obtainStyledAttributes(attributeSet, R.styleable.RangeEditText);
            charsAllowedMinimum = a.getInt(R.styleable.RangeEditText_charInputMinimum, DEFAULT_MINIMUM);
            charsAllowedMaximum = a.getInt(R.styleable.RangeEditText_charInputMaximum, DEFAULT_MAXIMUM);
        } finally {
            if (a != null) {
                a.recycle(); // ensure this is always called
            }
        }
    }
}

Step 3 - Use in XML

Now we have set up our attrs.xml file and our class to handle parsing of the attributes we can now use the attributes in an XML file in our project.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.kotikan.blogposts"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <com.kotikan.blogposts.views.RangeEditText
        android:id="@+id/range_edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:charInputMinimum="8"
        app:charInputMaximum="25"
        />

</LinearLayout>

Note use of xml namespace app "http://schemas.android.com/apk/res/com.kotikan.blogposts"

Step 4:

Up until lately (see r17 release notes) creating XML attributes for a library project’s custom view was not possible. What does this mean for the developer? Now our library code can become even more powerful by allowing us to set state of the custom view in our XML files which allows us to take advantage of the resource loading ability of Android. This means that we can alter the way our view looks dynamically just through creating another layout file and letting the android system take care of loading our views.

To achieve this we need to modify the XML file that defines our ‘app’ namespace. A simple one liner in the header of the XML file will take care of this for us:

   xmlns:app="http://schemas.android.com/apk/res-auto"

this URI is replaced with the specific app URI upon building the project thereby allowing you to use this in any project.

Conclusion

We have now successfully passed through state from our XML file to the class constructor. This has been applied at the project level (and provided you are using r17 or later) also for a library component.

I hope you, like us, find many uses for this trick.

Notes: 
An implementation of this example is freely available on github: git clone git@github.com:kotikan/blog-android-customAttributes.git

The code uses Maven3 to build - notes for how to use maven can be found at apache.org. Scroll to the section named “Installation Instructions” for help on how to set up your system.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android中的Dialog可以通过设置动画来实现一些特效,例如弹出、淡入淡出等效果。可以通过在Dialog的构造函数中使用`Window`对象来设置Dialog的动画。 下面是一个设置Dialog弹出动画的例子: ```java Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_dialog_layout); Window window = dialog.getWindow(); window.setGravity(Gravity.CENTER); window.setWindowAnimations(R.style.DialogAnimation); // 设置动画 dialog.show(); ``` 在res文件夹下新建一个anim文件夹,创建一个名为DialogAnimation的xml文件,用于设置Dialog的动画效果。例如: ```xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="100%p" android:toYDelta="0%p" android:duration="300" /> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" /> </set> ``` 这个例子中,设置了一个从下方弹出的动画效果,动画持续时间为300ms。你也可以通过修改这个动画文件来实现其他的动画效果。 ### 回答2: Android Dialog是Android系统提供的一种弹窗式界面,可以用来展示一些重要的信息或者与用户进行交互。在Android中,Dialog的显示和消失可以通过动画效果进行状态的切换。 Android提供了一些内置的Dialog动画效果,比如从屏幕的底部弹出、从屏幕的左右两侧滑入等,这些动画可以通过设置Dialog的Window动画样式来实现。具体来说,我们可以通过自定义style样式,将动画效果应用到Dialog的Window上。 首先,需要在res目录下的values文件夹中新建一个styles.xml文件,并在其中定义一个新的style样式,将其继承自android:Theme.Dialog。然后,在新的style样式中添加android:windowAnimationStyle属性,指定对应的动画资源文件。 动画资源文件是一个XML文件,可以通过translate、alpha、scale等属性来实现不同的动画效果。比如,可以使用translate属性设置位移动画,指定fromXDelta和toXDelta属性来控制X轴的位置变化。 最后,在调用Dialog的show()方法之前,通过调用dialog.getWindow().setWindowAnimations(R.style.dialogAnimation)方法,将动画效果应用到Dialog的Window上。其中,R.style.dialogAnimation是指之前定义的样式资源。 通过以上步骤,就可以实现自定义的Dialog动画效果了。可以根据具体的需求,定义不同的动画效果,增加了界面的交互性和用户体验。需要注意的是,要根据界面的逻辑合理选择动画效果,避免动画过度导致的界面混乱或卡顿的情况发生。 ### 回答3: Android Dialog动画是指在弹出对话框时设置的动画效果。通过设置动画效果,可以让对话框的弹出和隐藏更具有吸引力和流畅度。 Android提供了一些预定义的动画效果,如淡入淡出、上下滑动、放大缩小等。可以通过在Dialog对象上调用setWindowAnimations方法来设置对话框的动画效果。例如: dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; 其中,DialogAnimation是自定义的动画效果的样式资源。 此外,也可以自定义动画效果。首先,在res目录下创建res/anim文件夹,然后在该文件夹下创建自定义动画效果的xml文件,如slide_in.xml和slide_out.xml。在这些文件中,可以使用Android提供的动画属性来定义对话框的进入和退出动画,如alpha透明度动画、rotation旋转动画等。然后,在Dialog对象上调用setWindowAnimations方法,将自定义的动画效果指定给对话框。例如: dialog.getWindow().getAttributes().windowAnimations = R.style.CustomDialogAnimation; 其中,CustomDialogAnimation是自定义的动画效果的样式资源。 最后,需要注意的是,在使用动画效果时要考虑到对话框的加载时间和设备性能。如果动画效果过于复杂或加载时间过长,可能会影响用户体验或导致性能问题。因此,在设置动画效果时应谨慎选择,并进行适当的优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值