Why does setting imeActionId with a predefined ID resource create an error?

后端 未结 1 805
栀梦
栀梦 2020-12-03 03:36

Cyril Mottier has a great post on customizing the send/done/return key on the Android soft keyboard. When trying out the code, I (and several others in the comments) noticed

相关标签:
1条回答
  • 2020-12-03 04:09

    The reason is that imeActionId is a slight misnomer in this case. The Javadoc for imeActionId says:

    Supply a value for EditorInfo.actionId used when an input method is connected to the text view.

    It is looking for you to assign a value. A resource ID is for identifying resources in your app and does not have a guaranteed value. In some cases you can make comparisons based on resource ID's, such as View.getId(), but it is not good to mix resource ID's in with constant values that EditorInfo uses. Android may try to prevent you from doing this when it parses in your XML files by throwing exceptions like you saw, but there's not many checks it can do at runtime if you set it programmatically.

    Instead, you can define an integer value in your resources like so:

    <!--res/values/integers.xml-->
    <resources>
    <item type="integer" name="customImeActionId" format="integer">100</item>
    </resources>
    

    and use it like

    android:imeActionId="@integer/customImeActionId"
    

    In your code you can then retrieve it

    int imeActionId = getResources().getInteger(R.integer.customImeActionId);
    

    edit: OK, this has piqued my interest so looking further in the Android source code, TextView parses the attribute like:

    mEditor.mInputContentType.imeActionId = a.getInt(attr, mEditor.mInputContentType.imeActionId);
    

    It will use mEditor.mInputContentType.imeActionId as the default value -- which is 0 in this case -- if it can't find the int value of attr, which explains why it returns 0 if you use a newly created ID. I haven't found the cause of the inflation error.

    0 讨论(0)
提交回复
热议问题