Dropdown buttons / Spinner like the ones on the design specs from Google

后端 未结 2 1144
北荒
北荒 2021-02-04 16:17

I\'m wondering how can I do a dropdown button / menu like the ones we can see in the designs specs from Google and in the image bellow, so the list expands bellow right bellow t

2条回答
  •  死守一世寂寞
    2021-02-04 16:44

    Technically it's just a Spinner with custom views and styles.

    I tried to make one that looks similar to the one you posted, using AppCompat, working with custom drawables and with the view's elevation property, thus it may not completely work for Android versions older than 5.0.

    First let us define our Spinner with its dropdown properties:

    
    

    Important: We use the CustomSpinner class from this post, because we need the callbacks to know when the spinner opens an closes (for styling purposes).

    Then we setup the spinner: We use a custom View for the selected item (layout defined below) to apply our styles, and AppCompat's default R.layout.support_simple_spinner_dropdown_item, but we may use another layout to further adjust the styling.

    String[] data = {"Arial", "Calibri", "Helvetica", "Roboto", "Veranda"};
    
    ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_item_selected, data);
    adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
    
    final CustomSpinner spinner = (CustomSpinner) view.findViewById(R.id.spinner);
    spinner.setAdapter(adapter);
    spinner.setSpinnerEventsListener(new CustomSpinner.OnSpinnerEventsListener() {
        public void onSpinnerOpened() {
            spinner.setSelected(true);
        }
        public void onSpinnerClosed() {
            spinner.setSelected(false);
        }
    });
    

    And here the spinner_item_selected.xml layout:

    
    

    Further we need the drawables used above:

    spinner_bg.xml as the spinner's background:

    
        
        
        
            
                
                    
                    
                
            
        
    
    

    spinner_sla.xml to animate the spinner's elevation:

    
        
            
                
            
        
        
            
                
            
        
        
            
                
            
        
    
    

    This gives us a result like this (left collapsed, right open):

    If we want to use a spinner with images, we would also have to define a custom dropdown item view.

提交回复
热议问题