Programing

클릭 할 때 Android에서 버튼의 색상을 변경하는 방법은 무엇입니까?

lottogame 2020. 10. 18. 08:19
반응형

클릭 할 때 Android에서 버튼의 색상을 변경하는 방법은 무엇입니까?


Android 애플리케이션에서 작업 중입니다. 화면 하단에 4 개의 버튼을 수평으로 배치하고 싶습니다. 이 4 개의 버튼에는 2 개의 버튼에 이미지가 있습니다. 버튼의 테두리는 검은 색이어야하고 테두리는 가능한 한 얇아 야합니다. 버튼을 클릭하면 테두리 색상을 변경하지 않고 버튼의 배경을 파란색으로 변경하고 당분간 그 색상을 유지해야합니다. Android에서이 시나리오를 어떻게 달성 할 수 있습니까?


한 가지 방법은에서 drawablewhatever.xml이라는 XML 파일을 만드는 것입니다 .

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

    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item android:drawable="@drawable/bgnorm" />
</selector>

bgaltbgnorm당김의 PNG 이미지입니다.

활동에서 프로그래밍 방식으로 버튼을 만드는 경우 다음을 사용하여 배경을 설정할 수 있습니다.

final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));

XML로 버튼 스타일을 설정하면 다음과 같이 할 수 있습니다.

<Button
  android:id="@+id/mybutton"
  android:background="@drawable/watever" />

그리고 마지막으로 튜토리얼 링크 . 도움이 되었기를 바랍니다.


이 코드를 "bg_button.xml"을 사용하여 드로어 블 폴더에 저장하고 xml의 버튼 배경으로 "@ drawable / bg_button"을 호출합니다.

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#004F81" />
            <stroke
                android:width="1dp"
                android:color="#222222" />
            <corners
                android:radius="7dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#89cbee"
                android:endColor="#004F81"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#4aa5d4" />
            <corners
                android:radius="7dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

이것을 참조하십시오,

boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        check = true;
        backward_img.setBackgroundColor(Color.BLUE);
    }
});

if (check == true) {
    backward_img1.setBackgroundColor(Color.RED);
    backward_img.setBackgroundColor(Color.BLUE);
}

이 시도

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                button.setBackgroundColor(Color.RED);
            } else if(event.getAction() == MotionEvent.ACTION_DOWN) {
                button.setBackgroundColor(Color.BLUE);
            }
            return false;
        }

    });

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- default -->
    <item
        android:state_pressed="false"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#00a3e2" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />

        </shape>
    </item>

    <!-- button focused -->
    <item
        android:state_pressed="false"
        android:state_focused="true">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#5a97f5" />

            <padding
                android:bottom="5dp"
                android:left="10dp"
                android:right="10dp"
                android:top="5dp" />
        </shape></item>

    <!-- button pressed -->
    <item
        android:state_pressed="true"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#478df9"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape></item>
</selector>

버튼을 눌렀을 때 배경 이미지 또는 버튼의 색상을 변경하려면이 코드를 복사하여 아래 설명 된 정확한 위치에 프로젝트에 붙여 넣으십시오.

      <!-- Create new xml file like mybtn_layout.xml file in drawable -->
<?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/pressed" /> <!--pressed --> 
<item android:drawable="@drawable/normal" /> <!-- Normal -->
</selector>
  <!-- Now this file should be in a drawable folder and use this 
  single line code in    button code to get all the properties of this xml file -->

    <Button
      android:id="@+id/street_btn"
      android:layout_width="wrap_content"
      android:background="@drawable/layout_a" > <!-- your required code -->
    </Button>

이 시도......

먼저 button_pressed.xml이라는 xml 파일을 생성합니다. 이것이 내용입니다.

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

아니요 버튼에 이것을 시도하십시오.

int imgID = getResources().getIdentifier("button_pressed", "drawable", getApplication().getPackageName());
button.setImageResource(imgID);

button_pressed.xml은 드로어 블 폴더에 있어야합니다. icon_1_press 및 icon_1은 버튼 누름과 일반 초점에 대한 두 가지 이미지입니다.


이 코드를 사용하고 있습니다 (파급 효과 포함) :

<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/color_gray">
<item android:id="@android:id/mask">
    <color android:color="@color/color_gray" />
</item></ripple>

이 코드를 사용하여 문제를 해결할 수 있습니다.

<?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/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

드로어 블에이 코드를 작성하여 새 리소스를 만들고 원하는 이름을 지정한 다음 Android에서 이미지 src를 참조하는 것과 동일하게 버튼에이 drwable의 이름을 작성합니다.


public void onPressed(Button button, int drawable) {
            if (!isPressed) {
                button.setBackgroundResource(R.drawable.bg_circle);
                isPressed = true;
            } else {
                button.setBackgroundResource(drawable);
                isPressed = false;
            }
        }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.circle1:
                onPressed(circle1, R.drawable.bg_circle_gradient);
                break;
            case R.id.circle2:
                onPressed(circle2, R.drawable.bg_circle2_gradient);
                break;
            case R.id.circle3:
                onPressed(circle3, R.drawable.bg_circle_gradient3);
                break;
            case R.id.circle4:
                onPressed(circle4, R.drawable.bg_circle4_gradient);
                break;
            case R.id.circle5:
                onPressed(circle5, R.drawable.bg_circle5_gradient);
                break;
            case R.id.circle6:
                onPressed(circle6, R.drawable.bg_circle_gradient);
                break;
            case R.id.circle7:
                onPressed(circle7, R.drawable.bg_circle4_gradient);
                break;

        }

이것을 시도하십시오.이 코드에서 버튼을 클릭하면 버튼의 배경을 변경하려고합니다.


버튼을 다른 색상으로 유지하려는 시간을 적절하게 처리하려면이 버전을 권장합니다.

button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        button.setBackground(getResources().getDrawable(R.drawable.on_click_drawable));
                        break;
                    case MotionEvent.ACTION_UP:
                        new java.util.Timer().schedule(
                                new java.util.TimerTask() {
                                    @Override
                                    public void run() {
                                        ((Activity) (getContext())).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                button.setBackground(getResources().getDrawable(R.drawable.not_clicked_drawable));
                                            }
                                        });
                                    }
                                }, BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION);
                        break;
                    default:
                }
                return false;
            }
        });

BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION은 버튼이 이전 상태로 재설정 될 시간 [ms] 후를 나타냅니다 (그러나 달성하려는 항목에 따라 그 사이에 버튼이 사용되지 않았는지 확인하기 위해 일부 부울을 사용할 수 있음 ...) .


위의 주석 중 일부를 사용하더라도 필요한 사항을 해결하는 데 시간이 오래 걸렸습니다. 이 예제가 다른 사람에게 도움이되기를 바랍니다.

드로어 블 디렉토리에 radio_button.xml을 만듭니다.

    <?xml version="1.0" encoding="utf-8"?>

<!-- An element which allows two drawable items to be listed.-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/radio_button_checked" /> <!--pressed -->
    <item android:drawable="@drawable/radio_button_unchecked" /> <!-- Normal -->
</selector>

Then in the xml for the fragment should look something like

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">

<RadioButton

    android:id="@+id/radioButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_weight="1"
    android:button="@drawable/radio_button"
    android:paddingLeft="10dp" />        
<RadioButton
    android:id="@+id/radioButton2"
    android:layout_marginLeft="10dp"
    android:paddingLeft="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:button="@drawable/radio_button" />

</RadioGroup>
    </LinearLayout>
</layout>

hai the most easiest way is this:

add this code to mainactivity.java

public void start(View view) {

  stop.setBackgroundResource(R.color.red);
 start.setBackgroundResource(R.color.yellow);
}

public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}

and then in your activity main

    <button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">

</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">

or follow along this tutorial

참고URL : https://stackoverflow.com/questions/3882064/how-to-change-color-of-button-in-android-when-clicked

반응형