【问题标题】:Adding a custom view to XML... but with a GENERIC-type向 XML 添加自定义视图...但使用 GENERIC 类型
【发布时间】:2011-02-15 19:16:49
【问题描述】:

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

public class CustomViewFlipper<someType> extends ViewFlipper { }

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

【问题讨论】:

    标签: android xml generic-programming type-parameter


    【解决方案1】:

    由于类型参数实际上在字节码中被清除,您可以在 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);
    

    【讨论】:

      【解决方案2】:

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

      public class TheClassYouPutInTheLayoutFile extends CustomViewFlipper<someType>
      

      并在您的布局 XML 中使用该类。

      【讨论】:

      • 我认为,目前这是正确的答案,所以接受它。谢谢。
      • @CommonsWare - 您能否详细说明如何在布局 XML 中调用对象?我已经尝试了逻辑&lt;com.mynamespace.TheClassYouPutInTheLayoutFile .../&gt;,但我收到了一个异常Caused by: android.view.InflateException: Binary XML file line #70: Error inflating class ... Caused by: java.lang.NoSuchMethodException: &lt;init&gt; [class android.content.Context, interface android.util.AttributeSet]
      • @CrimsonX:如异常所示,需要实现两参数构造函数TheClassYouPutInTheLayoutFile(Context ctxt, AttributeSet attrs)
      • @CommonsWare - 你是绝对正确的 - 这是我刚刚发现的一个有用的问题,有助于解释更多关于 stackoverflow.com/questions/9054894/…的细节
      【解决方案3】:

      我使用这种方法,它对我有用。

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

      然后在activity中,如下实例化

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多