Defining custom attrs

前端 未结 5 1706
耶瑟儿~
耶瑟儿~ 2020-11-22 05:27

I need to implement my own attributes like in com.android.R.attr

Found nothing in official documentation so I need information about how to define these

5条回答
  •  名媛妹妹
    2020-11-22 05:46

    The answer above covers everything in great detail, apart from a couple of things.

    First, if there are no styles, then the (Context context, AttributeSet attrs) method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView) to get the TypedArray.

    Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.

    // Use your own name space if not using an android resource.
    final static private String ANDROID_NS = 
        "http://schemas.android.com/apk/res/android";
    private int pluralResource;
    private Resources resources;
    private String summary;
    
    public SeekBarPreference(Context context, AttributeSet attrs) {
        // ...
        TypedArray attributes = context.obtainStyledAttributes(
            attrs, R.styleable.SeekBarPreference);
        pluralResource =  attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
        if (pluralResource !=  0) {
            if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
                pluralResource = 0;
            }
        }
        if (pluralResource ==  0) {
            summary = attributes.getString(
                R.styleable.SeekBarPreference_android_summary);
        }
        attributes.recycle();
    }
    
    @Override
    public CharSequence getSummary() {
        int value = getPersistedInt(defaultValue);
        if (pluralResource != 0) {
            return resources.getQuantityString(pluralResource, value, value);
        }
        return (summary == null) ? null : String.format(summary, value);
    }
    

    • This is just given as an example, however, if you want are tempted to set the summary on the preference screen, then you need to call notifyChanged() in the preference's onDialogClosed method.

提交回复
热议问题