Adding a custom view to XML ... but using a GENERIC type

I am working on a custom view with the hope of being reused. It must be of a general type, for example:

public class CustomViewFlipper<someType> extends ViewFlipper { } 

I know how to associate a regular user view with an XML file. But I could not find any example for this situation. Is there a way to define a generic type for a class in XML?

+8
source share
3 answers

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

 public class TheClassYouPutInTheLayoutFile extends CustomViewFlipper<someType> 

and use this class in the XML layout.

+5
source

Since type parameters are actually cleared in bytecode, you can use the class name in XML as if it were not parameterized, and then passed it to the correct parameterized type in java code.

consider the class:

 public class CustomViewFlipper<T extends View> extends ViewFlipper { //... 

and in your xml action layout:

 <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); 
+9
source

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 action, create an instance as shown below

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

All Articles