Android: <declare-styleable> method attributes

我的梦境 提交于 2020-12-06 04:31:27

问题


How does one accept methods as values, in attributes? Like in the onClick attribute for a View:

<Button android:onClick="onClickMethod"/>

How to define custom attributes that accept methods?

I know we use <declare-styleable> in resources, but how do we make it accept methods?


回答1:


Android uses reflection to find the name of the method and invoke it. You can see an example in the source starting at line 4209 https://github.com/android/platform_frameworks_base/blob/master/core%2Fjava%2Fandroid%2Fview%2FView.java#L4209

             case R.styleable.View_onClick:
                if (context.isRestricted()) {
                    throw new IllegalStateException("The android:onClick attribute cannot "
                            + "be used within a restricted context");
                }

                final String handlerName = a.getString(attr);
                if (handlerName != null) {
                    setOnClickListener(new DeclaredOnClickListener(this, handlerName));
                }
                break;

If the method name isn't null, it creates a new DeclareOnClickListener() class and initializes it with the method name.

The DeclareOnClickListener() class is defined at line 4435 https://github.com/android/platform_frameworks_base/blob/master/core%2Fjava%2Fandroid%2Fview%2FView.java#L4435



来源:https://stackoverflow.com/questions/36580316/android-declare-styleable-method-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!