문제

내 활동에 8 개의 버튼이 있습니다. 내가 찾고있는 것은 버튼이 기본 배경을 가지고 있으며 버튼을 클릭하면 배경색이 다른 색으로 변경되어야합니다. 이 부분은 똑바로 앞으로 나아갑니다. 그러나 다른 버튼을 클릭하면 첫 번째 버튼의 배경색이 기본 색으로 다시 변경되어야합니다. 나는 이것이 "선택기 상태"를 사용하여 이루어질 것이라는 것을 이해하지만 그것을 구현하는 방법을 확신하지 못합니다. 더 읽을수록 그것에 대해 더 많이 읽을수록 더 혼란스러워합니다.

지금, 내가 가진 XML은 다음과 같습니다. Drawable 폴더에서

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

    <item android:drawable="@color/blue" android:state_pressed="true"/>
    <item android:drawable="@color/dark_grey" android:state_focused="true"/>  
    <item android:drawable="@drawable/image_border"/>

 </selector>
.

XML의 drawable / image_border는 버튼의 모양을 정의하는 데 사용됩니다. 아래는 image_border.xml

입니다
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="@color/dark_grey" />

    <stroke
        android:width="4dp"
        android:color="@color/light_grey" />

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

</shape>
.

누군가가 XML을 변경하는 방법을 사용하여 내가 필요로하는 방식으로 작동하는 방법을 어떻게 도와 줄 수 있습니까?

[편집 1]

아래의 모든 답변은 유사한 종류의 솔루션을 가리키고 있습니다. 내가 한 변화가있다. 그러나 단추를 누르면 지정된 색상으로 바뀌지 만 즉시 기본 색상으로 돌아갑니다.

button_background_blue.xml

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

    <item android:drawable="@drawable/image_border_blue" android:state_pressed="true"/>
    <item android:drawable="@color/dark_grey" android:state_focused="true"/>  
    <item android:drawable="@drawable/image_border"/>

 </selector>
.

image_border_blue.xml

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

    <solid android:color="@color/blue" />

    <stroke
        android:width="4dp"
        android:color="@color/blue" />

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

</shape>
.

어떤 생각?

도움이 되었습니까?

해결책

button_pressed.xml라는 모양 만들기

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

    <solid android:color="@color/blue" />

    <stroke
        android:width="4dp"
        android:color="@color/blue" />

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

</shape>
.

ID가 R.id.btnR.id.btn1 인 두 개의 버튼이 있습니다

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

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 1" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 2" />

</LinearLayout>
.

다른 버튼을 누를 때까지 변경된 색상을 유지할 수있는 onClick() 메서드를 작성합니다.

Button button;

public void onClick(View v) {

    Drawable dr = getResources().getDrawable(R.drawable.button_pressed);
    dr.setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.SRC_ATOP);

    switch (v.getId()) {
    case R.id.btn:

        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;

    case R.id.btn2:
        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;

    default:
        break;
    }
}
.

이제 당신이 원하는 것을 얻을 것이라고 생각합니다.

다른 팁

이 선택기를 사용하여이 선택 가능한 폴더에 넣고 버튼 배경을이 선택기로 설정하십시오.

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

<item android:drawable="@color/blue" android:state_pressed="true"/>
<item android:drawable="@color/AliceBlue" android:state_focused="true"/>  
<item android:drawable="@color/Azure"/>

 </selector>
.

또는 배경 대신 색상을 사용할 수 있습니다. 희망이 도움이됩니다.

이 선택기를 제안합니다.

Drawable 폴더에 Simple Selector.xml 파일을 만드고 android:background="@drawable/selector" 또는 다음과 같이 코드별로 선택기를 버튼에 추가하십시오. yourButton.setBackground(getResources().getDrawable(R.drawable.selector));

selector.xml :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true"
        android:state_focused="true" android:drawable="@android:color/holo_green_dark" />
    <item android:state_enabled="true"
        android:state_selected="true" android:drawable="@android:color/holo_purple" />
    <item
        android:drawable="@drawable/yourdrawable" />
</selector>
.

첫 번째 항목은 pressed에 대한 것입니다. focused의 두 번째이고 마지막은 selected 상태입니다.

changing background color in layout when respective color button is clicked in android

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b056ff"
    android:id="@+id/l1">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b1"
        android:layout_gravity="center"
        android:text="RED"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b2"
        android:layout_gravity="center"
        android:text="GREEN" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b3"
        android:layout_gravity="center"
        android:text="BLUE"/>

MyActivity.java

package ram.android.com.cwp1;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by VENKATESH on 10-Jun-16.
 */
public class MyActivity extends Activity implements View.OnClickListener {
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    Button r, g, b;
    LinearLayout ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        ll = (LinearLayout) findViewById(R.id.l1);
        r = (Button) findViewById(R.id.b1);
        g = (Button) findViewById(R.id.b2);
        b = (Button) findViewById(R.id.b3);
        r.setOnClickListener(this);
        g.setOnClickListener(this);
        b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.b1:
                ll.setBackgroundColor(Color.RED);
                break;

            case R.id.b2:
                ll.setBackgroundColor(Color.GREEN);
                break;
            case R.id.b3:
                ll.setBackgroundColor(Color.BLUE);
                break;

        }

    }
}

I know it is very late but I hope some one would find useful. I have very simple solution, I have used in my app and works awesome.

Let me explain the logic, 1. Keep track of 2 button clicks - previous button clicked and current button clicked. I am using ArrayList 2. for every button click keep updating the previous and current button clicks value in ArrayList. 3. change the background color of previous button clicked. 4. change the background color of current button clicked.

I hope the logic is simple and straightforward.

Here is the implementation

xml

<Button
            android:onClick="onClickRosterDay"
            android:text="Mon"
            android:textColor="@color/textColorWhite"
            android:background="@color/colorAccent"
            android:id="@+id/rosterMonday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

the OnClick method is defined for every button in XML, in the example it is onClickRosterDay

Java

 //buttons 

    Button rosterMonday;
    Button rosterTuesday;
    Button rosterWednesday;
    Button rosterThursday;
    Button rosterFriday;
    Button rosterSaturday;

    //ArrayList to track button clicks
    private ArrayList<Button> buttonClickedDay;

    in OnCreate

    buttonClickedDay = new ArrayList<>();
    // to start with these are the default clicks. 
    buttonClickedDay.add(rosterMonday ); //previous button clicked
    buttonClickedDay.add(rosterMonday ); // current button clicked



    public void onClickRosterDay(View v) {
            switch (v.getId()){
                case R.id.rosterMonday:
                    daySelected = "MONDAY";
                    // move current click button to previous button clicked position
                    buttonClickedDay.set(0, buttonClickedDay.get(1)); 
                    // update current clicked position
                    buttonClickedDay.set(1,rosterMonday);
                    break;

                case R.id.rosterTuesday:
                    daySelected = "TUESDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterTuesday);
                    break;

                case R.id.rosterWednesday:
                    daySelected = "WEDNESDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterWednesday);
                    break;

                case R.id.rosterThursday:
                    daySelected = "THURSDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterThursday);
                    break;

                case R.id.rosterFriday:
                    daySelected = "FRIDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterFriday);
                    break;

                case R.id.rosterSaturday:
                    daySelected = "SATURDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterSaturday);
                    break;
            }





        if(buttonClickedDay.get(0) != buttonClickedDay.get(1)) {
            // update background color of  previous button clicked    
buttonClickedDay.get(0).setBackgroundColor(this.getResources().getColor(R.color.colorAccent));
            // update background color of  current button clicked      
buttonClickedDay.get(1).setBackgroundColor(this.getResources().getColor(R.color.textBackgroundGreen));
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top