문제

나의 색상을 변경하는 표준이 안드로이드 단추를 약간하기 위해서 일치하는 클라이언트의 브랜드입니다.

최고의 방법을 발견했 이렇게하려면 지금까지 변경하는 것입 Button's 그릴 수를 그 위치 res/drawable/red_button.xml:

<?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/red_button_pressed" />
    <item android:state_focused="true" android:drawable="@drawable/red_button_focus" />
    <item android:drawable="@drawable/red_button_rest" />
</selector>

하지만 필요로 하는 실제로 만들기에 세 가지 다른 드로어 블 각 단추고 싶은 사용자 지정(하나의 버튼에서,나머지 하나의 초점을 맞추는 경우,그리고 한 때 누르면).는 것 같은 더 복잡한 과실을 나보다 필요합니다.

모든 정말 하고 싶은 적용하는 일종의 색 변환을 버튼입니다.이 있는 쉬운 방법에 대해 이동하는 변경 버튼을의 컬러보다는 내가 하고 있는가?

도움이 되었습니까?

해결책

나는 이것이 하나의 파일로 상당히 쉽게 수행 될 수 있음을 발견했다. 이름이 지정된 파일에 다음 코드와 같은 것을 넣으십시오. custom_button.xml 그런 다음 설정합니다 background="@drawable/custom_button" 버튼보기에서 :

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" >
        <shape>
            <gradient
                android:startColor="@color/yellow1"
                android:endColor="@color/yellow2"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

    <item android:state_focused="true" >
        <shape>
            <gradient
                android:endColor="@color/orange4"
                android:startColor="@color/orange5"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

    <item>        
        <shape>
            <gradient
                android:endColor="@color/blue2"
                android:startColor="@color/blue25"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

다른 팁

Tomasz의 답변에 따라 Porterduff Multiply 모드를 사용하여 전체 버튼의 그늘을 프로그래밍 방식으로 설정할 수도 있습니다. 이것은 색조가 아닌 버튼 색상을 변경합니다.

표준 회색 음영 버튼으로 시작하면 :

button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);

빨간색 음영 버튼을 줄 것입니다.

button.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);

첫 번째 값은 16 진 형식의 색상 인 녹색 음영 버튼 등을 제공합니다.

현재 버튼 색상 값에 색상 값을 곱하여 작동합니다. 이 모드로 할 수있는 더 많은 것이 있다고 확신합니다.

Mike, 당신은 컬러 필터에 관심이있을 수 있습니다.

An example:

button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000));

원하는 색상을 달성하려면 이것을 시도하십시오.

이것은 완벽하게 시작하는 내 솔루션입니다 API 15에서. 이 솔루션은 자료와 같은 모든 기본 버튼 클릭 효과를 유지합니다. RippleEffect. 낮은 API에서 테스트하지는 않았지만 작동해야합니다.

당신이해야 할 일은 다음과 같습니다.

1) 변화하는 스타일 만 만들어냅니다 colorAccent:

<style name="Facebook.Button" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@color/com_facebook_blue</item>
</style>

사용하는 것이 좋습니다 ThemeOverlay.AppCompat 또는 당신의 메인 AppTheme 부모로서 나머지 스타일을 유지합니다.

2)이 두 줄을 추가하십시오 button 위젯 :

style="@style/Widget.AppCompat.Button.Colored"
android:theme="@style/Facebook.Button"

때때로 당신의 새로운 colorAccent Android Studio Preview에는 표시되지 않지만 휴대 전화에서 앱을 시작하면 색상이 변경됩니다.


샘플 버튼 위젯

<Button
    android:id="@+id/sign_in_with_facebook"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="@string/sign_in_facebook"
    android:textColor="@android:color/white"
    android:theme="@style/Facebook.Button" />

Sample Button with custom color

이제 AppComPat-V7을 사용할 수도 있습니다 AppCompatbutton 이랑 backgroundTint 기인하다:

<android.support.v7.widget.AppCompatButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:backgroundTint="#ffaa00"/>

@conjugatedirection 및 @tomasz의 이전 답변에서 컬러 필터 제안을 좋아합니다. 그러나 지금까지 제공된 코드가 예상만큼 쉽게 적용되지 않았다는 것을 알았습니다.

첫째, 언급되지 않았습니다 어디 컬러 필터를 적용하고 지우려면. 이것을 할 다른 좋은 곳이있을 수 있지만, 나를 위해 떠오르는 것은 OntouchListener.

원래의 질문을 읽음으로써 이상적인 솔루션은 이미지와 관련이없는 솔루션입니다. @emmby의 custom_button.xml을 사용하여 허용 된 답변은 목표라면 컬러 필터보다 더 잘 맞을 것입니다. 제 경우에는 버튼의 모습에 대한 UI 디자이너의 PNG 이미지로 시작합니다. 버튼 배경을이 이미지로 설정하면 기본 하이라이트 피드백이 완전히 손실됩니다. 이 코드는 해당 동작을 프로그래밍 방식 어두워 진 효과로 대체합니다.

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 0x6D6D6D sets how much to darken - tweak as desired
                setColorFilter(v, 0x6D6D6D);
                break;
            // remove the filter when moving off the button
            // the same way a selector implementation would 
            case MotionEvent.ACTION_MOVE:
                Rect r = new Rect();
                v.getLocalVisibleRect(r);
                if (!r.contains((int) event.getX(), (int) event.getY())) {
                    setColorFilter(v, null);
                }
                break;
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                setColorFilter(v, null);
                break;
        }
        return false;
    }

    private void setColorFilter(View v, Integer filter) {
        if (filter == null) v.getBackground().clearColorFilter();
        else {
            // To lighten instead of darken, try this:
            // LightingColorFilter lighten = new LightingColorFilter(0xFFFFFF, filter);
            LightingColorFilter darken = new LightingColorFilter(filter, 0x000000);
            v.getBackground().setColorFilter(darken);
        }
        // required on Android 2.3.7 for filter change to take effect (but not on 4.0.4)
        v.getBackground().invalidateSelf();
    }
});

나는 이것을 여러 버튼에 적용하기위한 별도의 클래스로 추출했습니다. 아이디어를 얻기 위해 익명의 내부 클래스로 표시되었습니다.

XML을 사용하여 색상 버튼을 만드는 경우 별도의 파일로 집중된 상태 및 누름 상태를 지정하여 코드를 약간 더 깨끗하게 만들 수 있습니다. 내 녹색 버튼은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true" android:drawable="@drawable/button_focused"/>
    <item android:state_pressed="true" android:drawable="@drawable/button_pressed"/>

    <item>
        <shape>
            <gradient android:startColor="#ff00ff00" android:endColor="#bb00ff00" android:angle="270" />
            <stroke android:width="1dp" android:color="#bb00ff00" />
            <corners android:radius="3dp" />
            <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
        </shape>
    </item>

</selector>

모든 Android 버전으로 작동하는 가장 짧은 솔루션 :

<Button
     app:backgroundTint="@color/my_color"

메모/요구 사항:

  • 사용 app: 네임 스페이스 및 ~ 아니다 그만큼 android: 네임 스페이스!
  • AppCompat 버전> 24.2.0

    종속성 {compile 'com.android.support:appcompat-v7:25.3.1'}}

설명: enter image description here

이 접근법을 사용하고 있습니다

style.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:colorPrimaryDark">#413152</item>
    <item name="android:colorPrimary">#534364</item>
    <item name="android:colorAccent">#534364</item>
    <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

<style name="MyButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="android:colorButtonNormal">#534364</item>
    <item name="android:textColor">#ffffff</item>
</style>

위에서 볼 수 있듯이 버튼에 맞춤형 스타일을 사용하고 있습니다. 버튼 색상은 악센트 색상에 해당합니다. 나는 이것이 설정보다 훨씬 더 나은 접근법이라고 생각합니다 android:background Google이 제공하는 파급 효과를 잃지 않을 것입니다.

지금은 훨씬 쉬운 방법이 있습니다. Android-holo-colors.com

그것은 당신이 모든 Holo Drawables (버튼, 스피너, ...)의 색상을 쉽게 변경할 수 있습니다. 색상을 선택한 다음 모든 해상도에 대한 Drawables가 포함 된 zip 파일을 다운로드하십시오.

이런 식으로 사용하십시오.

buttonOBJ.getBackground().setColorFilter(Color.parseColor("#YOUR_HEX_COLOR_CODE"), PorterDuff.Mode.MULTIPLY);

~ 안에 <Button> 사용 android:background="#33b5e5". 또는 더 나은 android:background="@color/navig_button"

그만큼 드로이드 구성 요소 라이브러에는 a ColorButton XML 정의를 통해 및 실행 시간에 프로그래밍 방식으로 색상을 쉽게 변경할 수있는 위젯이므로 앱이 허용하는 경우 버튼의 색상/테마를 설정할 수 있습니다.

이 온라인 도구를 사용하여 버튼을 사용자 정의 할 수도 있습니다. http://angrytools.com/android/button/ 그리고 사용 android:background="@drawable/custom_btn" 레이아웃에서 사용자 정의 버튼을 정의합니다.

버튼의 테마를 이것으로 설정할 수 있습니다

<style name="AppTheme.ButtonBlue" parent="Widget.AppCompat.Button.Colored">
 <item name="colorButtonNormal">@color/HEXColor</item>
 <item name="android:textColor">@color/HEXColor</item>
</style>

는 쉬운 방법은 그냥 정의 사용자 정의 버튼 클래스는지의 모든 속성이 원하는 같은 반경,그라데이션을 누르면,컬러,정상적인 사용합니다.다음 사용에서는 XML 레이아웃을 대신의 설정을 사용하여 배경 XML.샘플링

이것은 매우 유용이 많을 경우의 버튼과 같은 특성을 같은 반경 선택,색상 등을 수 있다.사용자 정의할 수 있습 귀하의 상속를 처리하기 위해 버튼을 클릭한 추가적인 속성입니다.

결과(배경 없음 선택 사용되었다).

일반 버튼

Normal Image

버튼을 누르

enter image description here

잘 작동하는 다른 스타일 버튼을 수행하는 방법은 버튼 객체를 서브 클래스하고 컬러 필터를 적용하는 것입니다. 또한 버튼에 알파를 적용하여 활성화 및 비활성화 상태를 처리합니다.

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.Button;

public class DimmableButton extends Button {

    public DimmableButton(Context context) {
        super(context);
    }

    public DimmableButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DimmableButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void setBackgroundDrawable(Drawable d) {
        // Replace the original background drawable (e.g. image) with a LayerDrawable that
        // contains the original drawable.
        DimmableButtonBackgroundDrawable layer = new DimmableButtonBackgroundDrawable(d);
        super.setBackgroundDrawable(layer);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void setBackground(Drawable d) {
        // Replace the original background drawable (e.g. image) with a LayerDrawable that
        // contains the original drawable.
        DimmableButtonBackgroundDrawable layer = new DimmableButtonBackgroundDrawable(d);
        super.setBackground(layer);
    }

    /**
     * The stateful LayerDrawable used by this button.
     */
    protected class DimmableButtonBackgroundDrawable extends LayerDrawable {

        // The color filter to apply when the button is pressed
        protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
        // Alpha value when the button is disabled
        protected int _disabledAlpha = 100;
        // Alpha value when the button is enabled
        protected int _fullAlpha = 255;

        public DimmableButtonBackgroundDrawable(Drawable d) {
            super(new Drawable[] { d });
        }

        @Override
        protected boolean onStateChange(int[] states) {
            boolean enabled = false;
            boolean pressed = false;

            for (int state : states) {
                if (state == android.R.attr.state_enabled)
                    enabled = true;
                else if (state == android.R.attr.state_pressed)
                    pressed = true;
            }

            mutate();
            if (enabled && pressed) {
                setColorFilter(_pressedFilter);
            } else if (!enabled) {
                setColorFilter(null);
                setAlpha(_disabledAlpha);
            } else {
                setColorFilter(null);
                setAlpha(_fullAlpha);
            }

            invalidateSelf();

            return super.onStateChange(states);
        }

        @Override
        public boolean isStateful() {
            return true;
        }
    }

}

값 styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="RedAccentButton" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">#ff0000</item>
</style>

그 다음에:

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text"
    android:theme="@style/RedAccentButton" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text"
    android:theme="@style/RedAccentButton" />

result

재료 설계 지침에 따라 아래 코드와 같은 스타일을 사용해야합니다.

<style name="MyButton" parent="Theme.AppCompat.Light>
    <item name="colorControlHighlight">#F36F21</item>
    <item name="colorControlHighlight">#FF8D00</item>
</style>

그리고 레이아웃 에서이 속성을 버튼에 추가하십시오

    android:theme="@style/MyButton"

단순 .. 프로젝트 에이 종속성을 추가하고 1. 1의 버튼을 만듭니다. 모든 모양 2. 모든 색상 3. 물질 효과가있는 테두리 4.

https://github.com/manojbhadane/qbutton

<com.manojbhadane.QButton
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="OK"
       app:qb_backgroundColor="@color/green"
       app:qb_radius="100"
       app:qb_strokeColor="@color/darkGreen"
       app:qb_strokeWidth="5" />
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top