Android Custom Button

Have you ever wished you hade a better button option? A button with a better layout? Look no further :)

Creating a custom button!

It is actually really really easy to make a custom button. Just take a FrameLayout and add a predefined style from the android system we can make this FrameLayout looking like a button.

There are 4 nice styles to start with:

  • Widget.AppCompat.Button
  • button_style_button
  • Widget.AppCompat.Button.Colored
  • button_style_button_colored
  • Widget.AppCompat.Button.Borderless
  • button_style_button_borderless
  • Widget.AppCompat.Button.Borderless.Colored
  • button_style_button_borderless_colored

    So our FrameLayout would look like this after adding the Widget.AppCompat.Button style:

    
    
        ...
    
    

    And that is pretty much it. But lets look at some examples just for fun!

    Button with icon

    button_with_icon

    You have to set the text style as well to android:attr/textAppearanceButton on the TextView.

    
    
        
    
            
    
            
    
        
    

    Button with switch

    button_with_switch

    
    
        
    
            
    
            
    
            
    
        
    

    You can listen to the button click like this:

    View buttonWithSwitch = view.findViewById(R.id.button_with_switch);
    buttonWithSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            Log.d(TAG, "Button clicked!");
        }
    });
    
    Switch buttonSwitch = (Switch) buttonWithSwitch.findViewById(R.id.button_switch);
    buttonSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            Log.d(TAG, "Switch switched!");
        }
    });

    Or just get the switch status when onClick in the button occurs.

    View buttonWithSwitch = view.findViewById(R.id.button_with_switch);
    buttonWithSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            Switch buttonSwitch = (Switch) v.findViewById(R.id.button_switch);
            Log.d(TAG, "Button clicked! " + buttonSwitch.isChecked());
        }
    });

    Button with spinner

    We can pretty much create any kind of button we like. Here is one with a spinner.
    button_with_spinner

    
    
        
    
            
    
                
    
                
    
        
    

    Pretty easy right?

This Post Has One Comment

Leave a Reply

Close Menu