Get a specific statement from the list of states

I have a list of states that can be displayed, and I want to get a specific extract from the list of states:

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:kplus="http://schemas.android.com/apk/res-auto"> <item kplus:key_type_space_alt="true" android:state_pressed="true" android:drawable="@drawable/space_1_pressed" /> <item kplus:key_type_space_alt="true" android:drawable="@drawable/space_1_normal" /> <!-- TopNav keys. --> <item kplus:key_type_topnav="true" android:state_pressed="true" android:drawable="@drawable/tab_down" /> <item kplus:key_type_topnav="true" android:state_selected="true" android:drawable="@drawable/tab_down" /> <item kplus:key_type_topnav="true" android:drawable="@drawable/tab_normal" /> <!-- TopRow keys. --> <item kplus:key_type_toprow="true" android:state_pressed="true" android:drawable="@drawable/numeric_presseed" /> <item kplus:key_type_toprow="true" android:drawable="@drawable/numeric_normal" /> </selector> 

I choose the correct valid state for each key, something like this:

 if (keyIsNumbers) { if (KPlusInputMethodService.sNumbersState == 2) { drawableState = mDrawableStatesProvider.KEY_STATE_TOPNAV_CHECKED; } } 

Now the states are defined as follows:

 KEY_STATE_TOPNAV_NORMAL = new int[] {keyTypeTopNavAttrId}; KEY_STATE_TOPNAV_PRESSED = new int[] {keyTypeTopNavAttrId, android.R.attr.state_pressed}; KEY_STATE_TOPNAV_CHECKED = new int[] {keyTypeTopNavAttrId, android.R.attr.state_selected}; 

My question now is how to extract the correct value for each state? I need to get 9patch padding for drawable, because if the state has a different padding on 9patch, it will get padding only for the top drawable, and I want to manually configure padding for each key (drawable.getPadding (rect)).

+7
android android-layout android-input-method android-drawable statelistdrawable
source share
1 answer

There is no public API to get available from state.

There are a few methods in StateListDrawable , but they are @hide with the comment β€œpending API advice”.

You can call them a reflection ... but this is at your own peril and risk !!! . (it may change in future releases)

These methods:

Here's how to do it (exceptions omitted):

 int[] currentState = view.getDrawableState(); StateListDrawable stateListDrawable = (StateListDrawable)view.getBackground(); Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class); Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class); int index = (int) getStateDrawableIndex.invoke(stateListDrawable,currentState); Drawable drawable = (Drawable) getStateDrawable.invoke(stateListDrawable,index); 
+12
source share

All Articles