在不使用完全限定类名的情况下在XML中使用自定义视图

Rag*_*nar 9 android android-layout

我有自己的样式用于定义为主题的按钮,但我也使用自己的类来处理按钮(因为自己的字体).可以用一个漂亮的名字来调用我的按钮,例如

<MyButton>
Run Code Online (Sandbox Code Playgroud)

代替

<com.wehavelongdomainname.android.ui.MyButton>
Run Code Online (Sandbox Code Playgroud)

kco*_*ock 14

令人惊讶的是,答案是肯定的.我最近了解到这一点,实际上你可以采取一些措施来提高你的自定义视图通胀效率.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您为包含这些自定义视图的布局进行充气的任何活动或上下文中,您需要将工厂分配给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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在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>
Run Code Online (Sandbox Code Playgroud)