Same-named attributes in attrs.xml for custom view

前端 未结 5 915
夕颜
夕颜 2020-12-04 09:50

I\'m writing a few custom views which share some same-named attributes. In their respective section in attrs.xml I\'d lik

5条回答
  •  我在风中等你
    2020-12-04 10:29

    As Priya Singhal answered, Android Studio requires the common attribute names to be defined within their own style name. They can't be at the root any more.

    However, there are a couple other things to note (which is why I am also adding an answer):

    • The common styles don't need to be named the same thing as a view. (Thanks to this answer for pointing that out.)
    • You don't need to use inheritance with a parent.

    Example

    Here is what I did in a recent project that has two custom views that both share the same attributes. As long as the custom views still have the names for the attributes and don't include a format, I can still access them as normal from code.

    
    
    
        
    
        
            
            
            
            
                
                
                
            
        
    
        
    
        
            
            
            
            
        
    
        
            
            
            
            
        
    
    
    

    Streamlined example

    In fact, I don't even need to put the attributes under a custom name. As long as I define them (give them a format) for at least one custom view, I can use them anywhere (without the format). So this also works (and looks cleaner):

    
    
    
        
            
            
            
            
                
                
                
            
        
    
        
            
            
            
            
        
    
    
    

    For a large project, though, this could get messy and defining them at the top in a single location might be better (as recommended here).

提交回复
热议问题