使用XML格式的自定义视图,而无需使用完全限定类名自定义、视图、格式、XML

2023-09-04 06:02:39 作者:阿姨,借你儿子还你孙子

我有我自己的风格定义为主题的按钮,但我也用我自己的类来处理(因为自己的字体)按钮。是否可以打电话给我扣了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>