3

I have defined button style using selector with shape and kept the same in the drawable folder. Then attached it with the buttons in a layout file.

The button background color has been changed on pressing a button, but default color is showing after releasing the button. What I want is that the selected color should remain after button click. I need help. Thanks in advance.

Button style in drawable/highscore_button_style.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" >
        <shape android:shape="rectangle" >
            <solid android:color="@color/high_score_btn_bg_selected" />
            <corners android:radius="5dp" />
            <stroke android:color="@color/high_score_btn_bg_selected" android:width="1dp" />
        </shape>
    </item>
    <item android:state_pressed="true" >
        <shape android:shape="rectangle" >
            <solid android:color="@color/high_score_btn_bg_selected" />
            <corners android:radius="5dp" />
            <stroke android:color="@color/high_score_btn_bg_selected" android:width="1dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@color/high_score_btn_bg" />
            <corners android:radius="5dp" />
            <stroke android:color="@color/high_score_btn_bg" android:width="1dp" />
        </shape>
    </item>
</selector>

and buttons in layout file:

<Button
    android:id="@+id/btnLevel1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/highscore_button_style"
    android:layout_marginRight="1dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_weight="1"
    android:text="1"
    android:textColor="@color/high_score_btn_text" />
<Button
    android:id="@+id/btnLevel2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/highscore_button_style"
    android:layout_marginRight="1dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_weight="1"
    android:text="2"
    android:textColor="@color/high_score_btn_text" />
<Button
    android:id="@+id/btnLevel3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/highscore_button_style"
    android:layout_marginRight="1dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_weight="1"
    android:text="3"
    android:textColor="@color/high_score_btn_text" />
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
sayani
  • 148
  • 8

1 Answers1

0

Add following code in .java file

Button btn =(Button) findViewById(R.id.btnLevel1);
btn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    v.setSelected(true);
    // code here 
  }
});
Arshid KV
  • 9,631
  • 3
  • 35
  • 36