【问题标题】:How would I connect a customView to main activity我如何将 customView 连接到主要活动
【发布时间】:2020-12-06 21:43:07
【问题描述】:

我创建了一个 customView,它存储在 Layout 目录文件夹中。我想在主要活动 xml 布局中使用它(引用它)。我不知道如何将我的 customView 导入到主要活动及其 xml 中。这个 customView 没有自己的代码,它自己。我还没有弄清楚如何将我的 CustomView 连接到它自己的类。 一旦我能够在主要活动中使用我的 customView,我将把它放在一个 frameViewGroup 中。

附言将 customView 连接到 Activity 是否类似于将 customView 连接到自己的类?

【问题讨论】:

    标签: java android-studio kotlin android-custom-view main


    【解决方案1】:

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

    package gr.example.app.ui.layouts
    
    class MyView extends View {
       ....
    }
    

    那么在这种情况下你必须使用完整的包名

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

    但如果您在资源/布局文件夹中将其创建为 xml(假设它的名称是 my_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>
    

    那么你必须像这样在你的 main_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"/>
    

    【讨论】:

    • 我在 main_activity.xml 中使用它吗?每当我输入
    • 等等,我想我们可能有误会,我会更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多