Android: Custom View with object reference from attrs.xml, always null

我的梦境 提交于 2019-12-02 01:22:17

If your MorseKey class is in a separate java file, which I assume is the case from your statment "a class (that is not my activity)". Then I believe the problem is in your use of findViewById(). findViewById() will look for a resource within the MorseKey view itself rather than the main.xml file.

Maybe try getting the parent of the MorseKey instance and calling parent.findViewById().

case R.styleable.MorseKey_parentKey:
    parent = this.getParent().findViewById(a.getResourceId(attr, -1));

Though this will only work if your MorseKey parent and child are in the same layout.

<LinearLayout ...>
     <MorseKey ..../><!-- parent -->
     <MorseKey ..../><!-- child -->
</LinearLayout>

But it would be quite difficult to find the view if your layout is something like this with the parent and child in separate layouts.

<LinearLayout ...>
     <MorseKey ..../><!-- parent -->
</LinearLayout>
<LinearLayout ...>
     <MorseKey ..../><!-- child -->
</LinearLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!