【问题标题】:Using custom Views in XML without using fully-qualified class name在 XML 中使用自定义视图而不使用完全限定的类名
【发布时间】:2013-07-04 20:55:26
【问题描述】:

对于定义为主题的按钮,我有自己的风格,但我也使用自己的类来处理按钮(因为有自己的字体)。是否可以使用漂亮的名称来调用我的按钮,例如

<MyButton>

而不是

<com.wehavelongdomainname.android.ui.MyButton>

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    因此,令人惊讶的是,答案是“是”。我最近了解到这一点,实际上你可以做一些事情来让你的自定义视图膨胀更有效。 IntelliJ 仍然会警告您它无效(尽管它会成功编译和运行)——我不确定 Eclipse 是否会警告您。

    无论如何,你需要做的是定义你自己的LayoutInflater.Factory的子类:

    public class CustomViewFactory implements LayoutInflater.Factory {
        private static CustomViewFactory mInstance;
    
        public static CustomViewFactory getInstance () {
            if (mInstance == null) {
                mInstance = new CustomViewFactory();
            }
    
            return mInstance;
        }
    
        private CustomViewFactory () {}
    
        @Override
        public View onCreateView (String name, Context context, AttributeSet attrs) {
            //Check if it's one of our custom classes, if so, return one using
            //the Context/AttributeSet constructor
            if (MyCustomView.class.getSimpleName().equals(name)) {
                return new MyCustomView(context, attrs);
            }
    
            //Not one of ours; let the system handle it
            return null;
        }
    }
    

    然后,在任何活动或上下文中,您要在其中扩展包含这些自定义视图的布局,您需要将您的工厂分配给该上下文的 LayoutInflater:

    public class CustomViewActivity extends Activity {
        public void onCreate (Bundle savedInstanceState) {
            //Get the LayoutInflater for this Activity context
            //and set the Factory to be our custom view factory
            LayoutInflater.from(this).setFactory(CustomViewFactory.getInstance());
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout_with_custom_view);
        }
    }
    

    然后您可以在 XML 中使用简单的类名:

    <?xml version="1.0" encoding="utf-8"?>
    
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:orientation="vertical"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent">
    
        <MyCustomView
            android:id="@+id/my_view"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_gravity="center_vertical" />
    
    </FrameLayout>
    

    【讨论】:

    • Eclipse 告诉我没有 LayoutInflater.Factory
    • @Ragnar 自 API 1 (developer.android.com/reference/android/view/…) 以来就一直存在。您是否为它添加了正确的导入?
    • 找到了,我只需要导入android.view.LayoutInflater
    • 有趣的答案,但为什么它比使用完全限定名称更有效?编辑:没关系,您在 Marcin 的回答下方回答。没有这种反射将被使用,这将是 - 尽管很小 - 改进
    • @wasyl 只是避免使用反射来查找构造函数(因为您以这种方式直接调用它)。事情的方案没有太大的不同,因为我相信它无论如何都会缓存构造函数一段时间。我不会仅仅为了效率而实现这一点。 :)
    【解决方案2】:

    定义您自己的 LayoutInflater.Factory 子类对我来说似乎需要做很多工作。 只需使用一些通用代码覆盖 Activity 的 onCreateView():

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
    
        View view;
    
        // No need wasting microseconds getting the inflater every time.
        // This method gets called a great many times.
        // Better still define these instance variables in onCreate()
        if (mInflator == null){
    
            mInflator = LayoutInflater.from(context);
    
            mPrefix = ((Activity) context).getComponentName().getClassName();
    
            // Take off the package name including the last period
            // and look for custom views in the same directory.
            mPrefix = mPrefix.substring(0, mPrefix.lastIndexOf(".")+1);
        }
    
        // Don't bother if 'a path' is already specified.
        if (name.indexOf('.') > -1) return null;
    
        try{
    
            view = mInflator.createView(name, mPrefix, attrs);
    
        } catch (ClassNotFoundException e) {
    
            view = null;
    
        } catch (InflateException e) {
    
            view = null;
        }
    
        // Returning null is no big deal. The super class will continue the inflation.
        return view;
    }
    

    请注意,自定义视图必须与此 Activity 位于同一包中(即位于同一目录中),但它只是一段通用代码,您可以在任何 Activity 中添加(或者更好的是,从自定义父 Activity 继承班级)。 您不必担心寻找 kcoppock 提供的解决方案中指定的特定类:

    if (MyCustomView.class.getSimpleName().equals(name)) {....

    你肯定不是在创建一个全新的类。

    真正的魔力在于核心库类 LayoutInflator.java。请参阅下面的调用 mPrivateFactory.onCreateView()?:

        if (view == null && mPrivateFactory != null) {
            view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
        }
    
        if (view == null) {
            if (-1 == name.indexOf('.')) {
                view = onCreateView(parent, name, attrs);
            } else {
                view = createView(name, null, attrs);
            }
        }
    

    您会看到,如果所谓的 mPrivateFactory 返回 null(顺便说一下,mPrivateFactory 恰好是您的活动类),则 LayoutInflator 将继续使用它的其他替代方法并继续膨胀:

    if (view == null) {
       if (-1 == name.indexOf('.')) {
          view = onCreateView(parent, name, attrs);
       } else {
          view = createView(name, null, attrs);
       }
    }
    

    使用 IDE 调试器“遍历”库类并真正了解 Android 的工作原理是个好主意。 :)

    注意代码,if (-1 == name.indexOf('.')) {,适用于仍然坚持使用自定义视图放入完整路径的人,&lt;com.wehavelongdomainname.android.ui.MyButton&gt; 如果名称中有“点”,则调用 creatview()前缀(第二个参数)为空:view = createView(name, null, attrs);

    我之所以使用这种方法是因为我发现在初始开发过程中有时会移动(即更改)包名称。但是,与在 java 代码本身中执行的包名称更改不同,编译器不会捕获现在出现在任何 XML 文件中的此类更改和差异。使用这种方法,现在不必了。

    干杯。

    【讨论】:

      【解决方案3】:

      您也可以这样做:

      <view
        class="com.wehavelongdomainname.android.ui.MyButton" 
        ... />
      

      参见。 http://developer.android.com/guide/topics/ui/custom-components.html#modifying

      【讨论】:

      • 真的吗?这也适用于棒棒糖?这是一个新的:)
      • @milosmns 我不认为它是新的。 (也许你对你来说意味着新的。)
      • 是的,之前没用过。不错!
      【解决方案4】:

      没有。您需要为您的课程提供“完整路径”,否则框架将无法扩展您的布局。

      【讨论】:

      • 我在想有可能在 xml 中定义一个资源,它将这个类作为父类。不是吗?
      • @kcoppock 回答展示了如何帮助框架进行搜索,但我在这里还没有看到任何真正的好处。相当复杂的维护。
      • @MarcinOrlowski 在内部,如果您不提供 LayoutInflater,反射将用于扩展自定义视图,所以我会说这应该会提高性能(尽管我怀疑这会是一个明显的改进) ,但我同意它确实增加了一些开销。
      猜你喜欢
      • 2021-10-13
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 2011-08-26
      • 2013-06-21
      • 2012-07-01
      • 2020-11-12
      • 1970-01-01
      相关资源
      最近更新 更多