Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 618
eks Avatar asked Feb 15 '11 19:02

eks


People also ask

What are the options present while creating custom view?

Some examples of default views present in the Android Framework are EditText, TextView, Button, CheckBox, RadioButton, etc. ViewGroup is a special view that can contain other views (called children). We can create custom views and use them in our Application.


2 Answers

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);
like image 186
Tomasz Gawel Avatar answered Oct 16 '22 11:10

Tomasz Gawel


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.

like image 45
CommonsWare Avatar answered Oct 16 '22 09:10

CommonsWare