简体   繁体   中英

Android: how to use XML for custom view layout

I'm coming from the world of GWT and UIBinder, where I'm used to defining custom components by extending Composite, and then putting all the UI layout code in a MyComponent.ui.xml file. This is a very nice way to build up components from smaller pieces.

I'm trying to achieve the same effect on Android with custom Views. I've been able to programmatically extend View , and then add objects by calling addView(textView) . I'd like to be able to do that in XML, but I don't see how to associate an xml layout file with the view (apart the primary res/layout/main.xml file, which provides the primary layout for the app.

How can I layout my custom views in XML?

Edit: My question was unclear. What I'm looking to do is associate a my_widget.xml file with my customized view. Then in my_widget.xml I'd like to define various TextViews, etc, and plug them into my View class.

Use the fully qualified name of your custom view class in place of one of the built-in views. Here's a layout, for instance, that fills the window with your class:

<?xml version="1.0" encoding="utf-8"?>
<my.package.MyCustomView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

要从XML构造视图,请使用LayoutInflater

You can use findViewById (int id) with an id defined in XML. See the example in the android doc here (scroll down to IDs ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM