curioushikhov
curioushikhov

Reputation: 2838

How to create custom Button with using AppCompat library?

Is it possible to extend Button class without loosing AppCompat features like coloring/tinting/shadows?

For now, if I create custom class which extends Button and use it in layout it becomes white background/black foreground.

Upvotes: 0

Views: 2966

Answers (1)

curioushikhov
curioushikhov

Reputation: 2838

For example custom button:

package me.shikhov.buttontest;

import android.content.Context;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;

/**
 * Created by andrew on 19.01.16.
 */
public class MyButton extends
        AppCompatButton
{
    public MyButton(Context context) {
         this(context, null);
    }

    public MyButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

Example layout:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="me.shikhov.buttontest.MainActivity">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TEST BUTTON"
            android:layout_centerInParent="true"
            android:id="@+id/standard_button"
            />

        <me.shikhov.buttontest.MyButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:theme="@style/Widget.AppCompat.Button"
                android:text="MY BUTTON TEST"
                android:layout_centerHorizontal="true"
                android:layout_below="@id/standard_button"
                />

</RelativeLayout>

Important notes:

  1. MyButton should extend AppCompatButton and not android.view.Button

  2. You should explicitly set android:theme. That theme should be derived from Widget.AppCompat.Button theme.

Upvotes: 2

Related Questions