如何将customview连接到主活动

dxpyg8gm  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(339)

我创建了一个customview,它存储在layout目录文件夹中。我想在主活动xml布局中使用它(引用它)。我不知道如何将customview导入到主活动及其xml中。这个customview没有自己的代码,它本身就是。我还没有弄清楚如何将customview连接到它自己的类。一旦我能够在主活动中使用customview,我将把它放在frameviewgroup中。
p、 将customview连接到活动是否类似于将customview连接到自己的类?

3vpjnl9f

3vpjnl9f1#

如果您创建的自定义视图是通过代码创建的,例如:

package gr.example.app.ui.layouts

class MyView extends View {
   ....
}

在这种情况下,您必须使用完整的包名

<gr.example.app.ui.layouts.MyView>

但是如果您在resources/layouts文件夹中创建了一个xml(比如它的名称是my\u view.xml),如下所示:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="verical">

.....

</LinearLayout>

然后您必须在主\u activity.xml中使用include,如下所示:

<include
    android:id="@+id/my_custom_view" --this is optional, just another way to find the root view of layouts/my_view
    layout="@layouts/MyView"/>

相关问题