Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Custom Keyboard Change Background color key pressed

I ve got a problem and could not find a solution till yet! I ve implemented a custom keyboard with several keys. Each key got a background image. I would like to change the background color of the pressed key itself as shown in the original keyboard below:

enter image description here

I dont want to have a preview, I would like to change the background color of the key itself, when the key gets pressed. Here are my files:

keyboard.xml

<?xml version="1.0" encoding="UTF-8"?>
<android.inputmethodservice.KeyboardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/keyboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:keyPreviewOffset="10dp"
android:keyPreviewLayout ="@layout/preview"
android:keyTextColor="@color/colorAccent"
android:keyBackground="@drawable/keybackground"
android:background="#881f2023"
/>

keybackground.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:drawable="@drawable/cleanbuttonnormal" />
<item
    android:state_pressed="true"
    android:drawable="@drawable/cleandeactivate" />
<item
    android:state_checkable="true"
    android:drawable="@drawable/cleanbuttonnormal" />
<item
    android:state_checkable="true"
    android:state_pressed="true"
    android:drawable="@drawable/cleandeactivate" />
<item
    android:state_checkable="true"
    android:state_checked="true"
    android:drawable="@drawable/cleanbuttonnormal" />
<item
    android:state_checkable="true"
    android:state_checked="true"
    android:state_pressed="true"
    android:drawable="@drawable/keybackground" />
</selector>

The background color will be changed to my drawable, but when I hit the key, it will not changed to the pressed - state. The background stays the same. Could you please help me?

Here my custom keyboard layout, with preview enabled to show that the button got hit.

enter image description here

The black button with the 8 should get yellow. The preview is for debugging purposed.

like image 278
user3325230 Avatar asked Jul 29 '16 00:07

user3325230


1 Answers

The problem is with your state list in keybackground.xml. Here is excerpt from state list documentation:

During each state change, the state list is traversed top to bottom and the first item that matches the current state is used—the selection is not based on the "best match," but simply the first item that meets the minimum criteria of the state.

So in your case <item android:drawable="@drawable/cleanbuttonnormal" /> is selected every time. You should change order of items so the most specific items go first.

like image 147
Alexander Mironov Avatar answered Sep 30 '22 15:09

Alexander Mironov