代码之家  ›  专栏  ›  技术社区  ›  phunsoft

键入安卓:onClick标签布局中未显示XML文件。生成在没有警告的情况下完成

  •  0
  • phunsoft  · 技术社区  · 5 年前

    用Kotlin和androidstudio4.1开发Android应用程序。我在布局XML标记中输入了一个按钮的onClick函数的名称 安卓:onClick

    1. 我发现尽管有(明显的)问题,构建还是完成了,这让我很恼火。这是安卓工作室的预期成果吗?

    2. Android Studio确实标记了 “代码”选项卡 “XML文件”选项卡 . 这又是预期的行为吗?

      red,line indicating a problem

    注意:XML文件中有上述错误,添加的.kt文件中也有错误。

    0 回复  |  直到 5 年前
        1
  •  1
  •   a_local_nobody Dark_Clouds_369    5 年前

    enter image description here

    从图中可以看出,xml可以报告错误,您只需 打破 它。从这个意义上说,这意味着您必须键入它无法解析或理解的内容,例如试图定义一个不存在的属性。

    现在,就按钮单击侦听器而言,xml实际上并没有任何关于它将在何处使用的引用,除非您告诉它,通过在根布局中使用上下文:

    tools:context="your_activity_here"
    

    完整示例:

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.overview.OverviewActivity"> //<-- this is key
    

    enter image description here

    但是,这仍然会编译和安装,而且这里不会有任何编译时问题,所以这对您的情况不会有任何帮助


    也许一个更好的方法应该是询问为什么仍然在xml中定义这些单击侦听器,而kotlin为我们提供了合成的导入。下面是一个例子:

    与在xml文件中定义单击侦听器不同,下面的方法也是有效的:

            <Button
            android:id="@+id/myButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ...
    

        myButton.setOnClickListener { //this is the ID of the component in xml you're trying to access
          //your logic here
        }
    

    这是因为kotlin有一个叫做synthetic imports的特性,它允许我们通过导入整个文件直接访问xml组件,例如:

    import kotlinx.android.synthetic.main.example.*
    

    为什么我觉得这样更好?(个人意见)

    有编译时错误,如果找不到组件,将阻止您生成

        2
  •  0
  •   Akash kumar    5 年前

    在活动中导入的布局中, 将onClick()放在元素中,并将其引用到导入onClick listner的活动中安卓:onClick=“一次点击”

    enter image description here