Android: how to use XML for custom view layout

I come from the world of GWT and UIBinder, where I am used to defining custom components by expanding Composite and then putting all the UI layout code in MyComponent.ui.xml. This is a very good way to create components from smaller parts.

I am trying to achieve the same effect on Android with custom views. I was able to programmatically expand Viewand then add objects by calling addView(textView). I would like to be able to do this in XML, but I do not see how to associate the xml layout file with the view (except for the main file res/layout/main.xml, which provides the main layout for the application.

How can I put my own views in XML?

Edit: My question was unclear. What I want to do is link the file my_widget.xmlto my customized view. Then in my_widget.xml I would like to define various TextViews, etc. And connect them to the View class.

+3
source share
3 answers

To build views from XML, use LayoutInflater .

+3
source

Instead of one of the built-in views, use the fully qualified name of your custom view class. Here, for example, is a layout 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"
    />
+13
source

findViewById (int id) , XML. . android doc ( ID).

0

Source: https://habr.com/ru/post/1789018/


All Articles