androiddeclare-styleable

Android: <declare-styleable> method attributes


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?


Solution

  • 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