16

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?

SOFe
  • 7,867
  • 4
  • 33
  • 61
eks
  • 501
  • 4
  • 13

3 Answers3

11

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I think, currently this is the correct answer, so accepting it. Thanks. – eks Feb 18 '11 at 11:40
  • @CommonsWare - Can you expand upon how you call the object in layout XML? I've tried the logical `` but I recieve an exception `Caused by: android.view.InflateException: Binary XML file line #70: Error inflating class ... Caused by: java.lang.NoSuchMethodException: [class android.content.Context, interface android.util.AttributeSet]` – CrimsonX Sep 06 '13 at 20:19
  • 1
    @CrimsonX: As the exception indicates, you need to implement the two-parameter constructor `TheClassYouPutInTheLayoutFile(Context ctxt, AttributeSet attrs)`. – CommonsWare Sep 06 '13 at 20:28
  • @CommonsWare - you're absolutely right - here's a helpful question that I just found that helps explain a little bit more detail about this http://stackoverflow.com/questions/9054894/custom-surfaceview-causing-nosuchmethodexception – CrimsonX Sep 06 '13 at 20:31
10

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);
Tomasz Gawel
  • 8,379
  • 4
  • 36
  • 61
0

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)
Elye
  • 53,639
  • 54
  • 212
  • 474