Use declare styleable to set custom component input type

前端 未结 4 567
耶瑟儿~
耶瑟儿~ 2020-12-14 06:18

I have a CompositeComponent (EditText+ImageButton) When clicking on button the edittext content will be cleared. It is working fine. My problem is setting attributes to my c

4条回答
  •  -上瘾入骨i
    2020-12-14 06:43

    Lets say you have a custom view named InputView, which is not a TextView (lets say its a RelativeLayout).

    In your attrs.xml:

    
    
        
         
    
        
         
        
    
    
    

    In an xml layout where you want to include InputView:

    
    
    
            
            
            
    
    
    

    Inside your custom class you can extract attributes as usual:

        ...
    
        private String title;
        private int inputType;
        private int imeOptions;
    
        ...
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.InputView);
    
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
            case R.styleable.InputView_title:
                title = a.getString(attr);
                break;
            //note that you are accessing standart attributes using your attrs identifier
            case R.styleable.InputView_android_inputType:
                inputType = a.getInt(attr, EditorInfo.TYPE_TEXT_VARIATION_NORMAL);
                break;
            case R.styleable.InputView_android_imeOptions:
                imeOptions = a.getInt(attr, 0);
                break;
            default:
                Log.d("TAG", "Unknown attribute for " + getClass().toString() + ": " + attr);
                break;
            }
        }
    
        a.recycle();
        ...
    

提交回复
热议问题