Adding a custom view to XML… but with a GENERIC-type

让人想犯罪 __ 提交于 2019-12-05 18:34:38

问题


I am working on a custom view with a hope of reusability. It should have a generic type, like this:

public class CustomViewFlipper<someType> extends ViewFlipper { }

I know how to bind a normal custom view to the XML file. But I couldn't find any example for this situation. Is there any way to define a generic type for a class in XML?


回答1:


I don't think so, but you can create your own subclass:

public class TheClassYouPutInTheLayoutFile extends CustomViewFlipper<someType>

and use that class in your layout XML.




回答2:


As type parameters are actually cleared off in bytecode, you can use in XML the class name as if it was not parametrized and then cast it to proper parametrized type in java code.

consider having class:

public class CustomViewFlipper<T extends View> extends ViewFlipper { 

    //...

and in your activities layout xml:

<view 
    class="com.some.package.CustomViewFlipper"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/customFlipper"/>

then in your activity:

@Override
protected void onCreate(Bundle savedInstanceState) {

    //...
    @SuppressWarnings("unchecked")
    CustomViewFlipper<TextView> customFlipper = 
            (CustomViewFlipper<TextView>) findViewById(R.id.customFlipper);



回答3:


I use this approach and it works for me.

    <com.some.package.CustomViewFlipper
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/customFlipper"/>

And then in the activity, instantiate as below

    CustomViewFlipper<someType> customFlipper = 
        (CustomViewFlipper<someType>) findViewById(R.id.customFlipper)


来源:https://stackoverflow.com/questions/5008426/adding-a-custom-view-to-xml-but-with-a-generic-type

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