从 xml 布局访问自定义视图
在 Android 应用程序中,我创建了一个扩展 View
类的自定义视图。我想在 xml 布局文件中声明我的类的一个对象,但是,即使经过多次尝试,应用程序在执行 setContentView
调用时也会意外停止(这就是出现的弹出窗口所说的内容)。< br> 在我的 MainActivity
文件中声明为 public 的视图类中,我有两个构造函数:一个仅使用 Context
作为参数,另一个使用 Context< /code> 和
AttributeSet
参数。我已经重写了 onDraw
函数。
这个类位于我的源包中,名为org.me.myapp
。 在布局文件中,我声明要插入的对象,如下所示:
<org.me.myApp.MainActivity.myView"
android:id="@+id/View"
android:layout_below="@id/toto"
android:layout_width="300dip"
android:layout_height="100dip"/>
任何人都可以告诉我出了什么问题吗?
预先感谢您花时间帮助我。
In an Android application, I have created a custom view extending the View
class. I want to declare an object of my class in the xml layout file but, even after many tries, the application unexpectedly stops when the setContentView
call is executed (that's what the popup windows which appears says).
In my view class, which is declared in my MainActivity
file as public, I have two constructors : one with only the Context
as parameter and one with a Context
and an AttributeSet
parameters. And I have overridden the onDraw
function.
This class is in my source package, named org.me.myapp
.
In the layout file, I declare the object I want to insert like this :
<org.me.myApp.MainActivity.myView"
android:id="@+id/View"
android:layout_below="@id/toto"
android:layout_width="300dip"
android:layout_height="100dip"/>
Can anyone tell me what is wrong?
Thanks in advance for the time you will spend trying to help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Yar 所说,您应该扩展 View 或 ViewGroup 来创建自定义布局元素,并在布局 xml 中使用该类名称。不是成员变量看起来你正在尝试做的事情。展开布局后,您可以使用以下方式访问自定义视图:
What Yar said, you should extend View or ViewGroup to create custom layout element, and use that class name in your layout xml. Not member variable what it looks you're trying to do. After inflating your layout you can access your custom view with;
我认为您需要将自定义布局声明为单独的类,例如: org.me.myapp.MyView 并在 xml 文件中将其关联起来,如下所示:
I think you need to declare your custom layout as a separate class, for example: org.me.myapp.MyView and relate to it in your xml file like this: