使用XML格式的自定义视图,而无需使用完全限定类名 [英] Using custom Views in XML without using fully-qualified class name

查看:72
本文介绍了使用XML格式的自定义视图,而无需使用完全限定类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我自己的风格定义为主题的按钮,但我也用我自己的类来处理(因为自己的字体)按钮。是否可以打电话给我扣了pretty的名称,如

I have my own style for buttons defined as themes but I also use my own class to handle buttons (because of own fonts). Is it possible to call my button with a pretty name such as

<MyButton>

而不是


推荐答案

因此​​,答案令人惊讶的,是yes。我得知这个最近,它实际上是你可以做,使您的自定义视图通胀更有效。的IntelliJ仍警告你,它的无效的(虽然会编译和运行成功) - 我不知道的Eclipse是否向您发出警告与否

So the answer, surprisingly, is "yes". I learned about this recently, and it's actually something you can do to make your custom view inflation more efficient. IntelliJ still warns you that its invalid (although it will compile and run successfully) -- I'm not sure whether Eclipse warns you or not.

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

Anyway, so what you'll need to do is define your own subclass of 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:

You can then use the simple class name in your 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>

这篇关于使用XML格式的自定义视图,而无需使用完全限定类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆