如何将CustomView添加到布局

时间:2015-06-04 20:55:52

标签: java android xml layout

我知道有很多关于“如何将CustomView添加到布局”的问题,但我几乎阅读了所有内容,我仍然有问题。 XML中的CustomView

<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恨我:(

我不知道问题出在哪里

感谢您的回答

2 个答案:

答案 0 :(得分:1)

我发现了这个小问题here

  

要允许Android开发者工具与您的视图互动, at a   最低 您必须提供一个带 上下文和 的构造函数    AttributeSet 对象作为参数。此构造函数允许布局   编辑器,用于创建和编辑视图的实例。

似乎部分问题已涵盖here

至于@drawable/brown我猜测它与系统不兼容,或者你搞砸了你创建它的文件。但是因为我不知道什么是可绘制的(提示提示,请提供相应的代码!),我无法确切地告诉您它为什么不能编译,但是是的,您在命名时需要使用全部小写字母,所以{{1}是正确的。

尝试重新启动Android Studio。

答案 1 :(得分:0)

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

 <slccs.drawingapplication.DrawLine

表示您在包中有一个类DrawLine: “slccs.drawingapplication”

其次,android期望文件名以小写字母开头,只包含字母数字字符和' - '或'。'。

所以一定要在你的drawable文件夹中复制棕色图片并告诉我们现在一切正常