如何将自定义视图添加到布局

How to add CustomView to layout

我知道有很多关于 "How to add CustomView to Layout" 的问题,但我几乎阅读了所有问题,但我仍然有问题。 XML

中的自定义视图
<slccs.drawingapplication.DrawLine
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/drawline"/>

和Java这个视图的代码

package slccs.drawingapplication; import android.content.Context; import android.view.View;

public class DrawLine extends View {

public DrawLine(Context c){
    super(c);
}}

我遇到了这个错误The following classes could not be found:- slccs.drawingapplication.DrawLine

当我清理项目时,我会收到更多错误:

Error:Error: Invalid file name: must contain only lowercase letters and digits ([a-z0-9_.]) 这是关于我的 @drawable/Brown 图片文件。因此,当我将 B 更改为 b 时,我会在 activity_main xml 文件中遇到新问题:

Couldn't resolve resource @drawable/brown

Failed to convert @drawable/brown into a drawable

我认为今天是 AndroidStudio 讨厌我:(

不知道哪里出了问题

感谢您的回答

public class DrawLine extends View {

public DrawLine(Context c){
    super(c);
}

public DrawLine(Context context, AttributeSet attrs) {
    super(c);
}
}

首先在您的布局中声明此自定义视图:

 <slccs.drawingapplication.DrawLine

意味着你有一个 class DrawLine 位于包中: "slccs.drawingapplication"

其次,android 期望文件名以小写字母开头并且仅包含字母数字字符和“-”或“.”。

所以请确保您已将棕色图片复制到可绘制文件夹中,并告诉我们现在是否一切正常

我找到了这个花絮 here

To allow the Android Developer Tools to interact with your view, at a minimum you must provide a constructor that takes a Context and an AttributeSet object as parameters. This constructor allows the layout editor to create and edit an instance of your view.

您的部分问题似乎已涵盖 here

至于 @drawable/brown 我猜它要么与系统不兼容,要么你在创建它的文件中搞砸了。但是因为我不知道 drawable 是什么(提示提示,请为它编写代码!),我真的不能确切地告诉你为什么它不能编译,但是是的,你确实需要在命名它时全部使用小写字母,所以 brown.yourfiletype 是正确的。

尝试重新启动 Android Studio。