Làm thế nào để thay đổi màu của nút trong Android khi được nhấp?


81

Tôi đang làm việc trên Ứng dụng Android. Tôi muốn có 4 nút được đặt theo chiều ngang ở dưới cùng của màn hình. Trong 4 nút này, 2 nút đang có hình ảnh trên đó. Đường viền của các nút phải có màu đen và viền càng mỏng càng tốt. Khi tôi nhấp vào nút, tôi muốn nền của nút sẽ được thay đổi thành màu xanh lam mà màu của đường viền không bị thay đổi và nên giữ nguyên màu đó trong một thời gian. Làm cách nào để đạt được tình huống này trong Android?


Có thể trùng lặp của Làm thế nào để thay đổi màu sắc của vector đường drawable vào nút bấm tôi gắn cờ nó như trùng lặp, bạn có thể kiểm tra câu trả lời của tôi ở đây: stackoverflow.com/a/55205149/3763032
mochadwi

Câu trả lời:


128

Một cách tiếp cận là tạo một tệp XML như thế này drawable, có tên là anything.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>

bgaltbgnormlà hình ảnh PNG có thể vẽ được.

Nếu bạn tạo các nút theo chương trình trong hoạt động của mình, bạn có thể đặt nền bằng:

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

Nếu bạn đặt kiểu nút của mình bằng XML, bạn sẽ làm như sau:

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

Và cuối cùng là một liên kết đến một hướng dẫn . Hi vọng điêu nay co ich.


16
Bạn cũng có thể thay thế các bảng có thể vẽ đó trong tệp XML bằng các định nghĩa về màu sắc nếu bạn muốn tránh sử dụng hình ảnh.
haseman 7/10/10

7
@ jshin47 một số thử nghiệm và sai sót. Tôi đã viết hai cuốn sách về phát triển Android ngay bây giờ :-)
haseman

@haseman - Bạn có thể đăng link của 2 cuốn sách đó hoặc chia sẻ cho mình tại brk0018@gmail.com. Rất vui khi trải qua những điều đó và học tốt hơn
Ramakishna Balla

1
Điều gì xảy ra nếu chỉ màu sắc không phải hình ảnh?
Kala J

@KalaJ bạn đã tìm ra giải pháp chưa?
Prafulla Kumar Sahu

75

Lưu mã này trong thư mục có thể vẽ với "bg_button.xml" và gọi "@ drawable / bg_button" làm nền của nút trong xml của bạn:

<?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>

2
Cảm ơn anh bạn, sử dụng phong cách bạn có thể giảm kích thước ứng dụng. ý tưởng tốt để không sử dụng drawable
Rahul Mandaliya

Mặt khác, các tệp có thể kéo dựa trên vector xml thường kém hơn về hiệu suất so với hình ảnh, đặc biệt là trên các thiết bị cũ hơn. Đừng tối ưu hóa quá sớm, nhưng hãy ghi nhớ điều đó.
Przemyslaw Jablonski

10

Thử đi

    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;
        }

    });

9

Tham khảo điều này,

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);
}

2
Thao tác này sẽ đặt BG vĩnh viễn, nghĩa là nếu người dùng nhấp vào nút quay lại, nền sẽ có màu đỏ.
metode

@methode: ok tham khảo câu trả lời mới tôi đã sửa chữa các oldanswer
Sankar Ganesh PMP

8
<?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>

6

Nếu bạn muốn thay đổi hình ảnh backgorund hoặc màu sắc của nút khi nó được nhấn, thì chỉ cần sao chép mã này và dán vào dự án của bạn tại vị trí chính xác được mô tả bên dưới.

      <!-- 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>

4

Thử đi......

Đầu tiên hãy tạo một tệp xml có tên button_pressed.xml Đây là nội dung của nó.

<?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>

Noe hãy thử điều này trên nút của bạn.

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

button_pressed.xml phải nằm trong thư mục có thể vẽ được. icon_1_press và icon_1 là hai hình ảnh để nhấn nút và lấy nét bình thường.


2

1-tạo 1 hình dạng cho Nút nhấp chuột phải vào tệp tài nguyên có thể vẽ và tệp tài nguyên mới có thể vẽ được. thay đổi phần tử Root để định hình và tạo hình dạng của bạn.

nhập mô tả hình ảnh ở đây

2-bây giờ tạo 1 bản sao từ hình dạng của bạn và thay đổi tên và thay đổi màu đặc. nhập mô tả hình ảnh ở đây

Nhấp chuột phải 3 lần vào tệp tài nguyên có thể vẽ và mới có thể vẽ chỉ đặt phần tử gốc thành bộ chọn.

đi tới tệp và đặt "state_pressed"

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"android:drawable="@drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="@drawable/YourShape2"/>

</selector>

4-cuối đi đến bố cục xml và đặt nền Nút của bạn "bộ chọn của bạn"

(xin lỗi vì tiếng anh của tôi yếu)


1

Tôi đang sử dụng mã này (với hiệu ứng gợn sóng):

<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>

1

bạn có thể thử mã này để giải quyết vấn đề của bạn

<?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>

viết mã này trong có thể vẽ của bạn, tạo một tài nguyên mới và đặt tên cho nó theo ý bạn muốn và sau đó viết tên của tài nguyên có thể kéo này vào nút giống như chúng ta tham khảo image src trong android


1
chào ông @lmo Tôi đã đưa ra một số lời giải thích với câu hỏi.
Mudassir Khan,

1
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;

        }

Vui lòng thử cái này, trong đoạn mã này, tôi đang cố gắng thay đổi nền của nút trên nút bấm vào nút này hoạt động tốt.


0

Để giải quyết chính xác trong bao lâu bạn muốn nút của mình ở màu khác, tôi sẽ tư vấn cho phiên bản này:

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 cho biết sau bao nhiêu thời gian [mili giây] nút sẽ đặt lại về trạng thái trước đó (tuy nhiên bạn có thể muốn sử dụng một số boolean để kiểm tra xem nút đó chưa được sử dụng ở giữa hay không, tùy thuộc vào những gì bạn muốn đạt được ...) .


0

Ngay cả khi sử dụng một số nhận xét ở trên, điều này cũng mất nhiều thời gian hơn để tìm ra điều cần thiết. Hy vọng rằng ví dụ này sẽ giúp ích cho người khác.

Tạo một radio_button.xml trong thư mục có thể vẽ được.

    <?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>

Sau đó, trong xml cho phân đoạn sẽ trông giống như

<?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>

-1

hai cách dễ nhất là:

thêm mã này vào 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);
}

và sau đó trong hoạt động chính của bạn

    <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">

hoặc làm theo hướng dẫn này

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.