问题 将自定义视图添加到XML ...但使用GENERIC类型


我正在开发一个自定义视图,希望可重用。它应该有一个泛型类型,如下所示:

public class CustomViewFlipper<someType> extends ViewFlipper { }

我知道如何将普通的自定义视图绑定到XML文件。但我找不到这种情况的任何例子。有没有办法为XML中的类定义泛型类型?


4909
2018-02-15 19:16


起源



答案:


我不这么认为,但你可以创建自己的子类:

public class TheClassYouPutInTheLayoutFile extends CustomViewFlipper<someType>

并在布局XML中使用该类。


5
2018-02-15 20:22



我想,目前这是正确的答案,所以接受它。谢谢。 - eks
@CommonsWare - 你能扩展一下如何在布局XML中调用对象吗?我试过这个逻辑 <com.mynamespace.TheClassYouPutInTheLayoutFile .../> 但我接受了一个例外 Caused by: android.view.InflateException: Binary XML file line #70: Error inflating class ... Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet] - CrimsonX
@CrimsonX:如异常所示,您需要实现双参数构造函数 TheClassYouPutInTheLayoutFile(Context ctxt, AttributeSet attrs)。 - CommonsWare
@CommonsWare - 你是完全正确的 - 这是一个有用的问题,我刚刚发现它可以帮助解释一些关于这一点的更多细节 stackoverflow.com/questions/9054894/... - CrimsonX


答案:


我不这么认为,但你可以创建自己的子类:

public class TheClassYouPutInTheLayoutFile extends CustomViewFlipper<someType>

并在布局XML中使用该类。


5
2018-02-15 20:22



我想,目前这是正确的答案,所以接受它。谢谢。 - eks
@CommonsWare - 你能扩展一下如何在布局XML中调用对象吗?我试过这个逻辑 <com.mynamespace.TheClassYouPutInTheLayoutFile .../> 但我接受了一个例外 Caused by: android.view.InflateException: Binary XML file line #70: Error inflating class ... Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet] - CrimsonX
@CrimsonX:如异常所示,您需要实现双参数构造函数 TheClassYouPutInTheLayoutFile(Context ctxt, AttributeSet attrs)。 - CommonsWare
@CommonsWare - 你是完全正确的 - 这是一个有用的问题,我刚刚发现它可以帮助解释一些关于这一点的更多细节 stackoverflow.com/questions/9054894/... - CrimsonX


由于类型参数实际上是在字节码中清除的,因此您可以在XML中使用类名,就像它没有参数化一样,然后在java代码中将其转换为适当的参数化类型。

考虑上课:

public class CustomViewFlipper<T extends View> extends ViewFlipper { 

    //...

并在您的活动布局xml中:

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

然后在你的活动中:

@Override
protected void onCreate(Bundle savedInstanceState) {

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

9
2017-07-03 16:53





我使用这种方法,它适用于我。

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

然后在活动中,实例化如下

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

-1
2017-12-10 14:23