从 xml 布局访问自定义视图

发布于 2024-10-29 06:30:47 字数 681 浏览 5 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若有似无的小暗淡 2024-11-05 06:30:47

正如 Yar 所说,您应该扩展 View 或 ViewGroup 来创建自定义布局元素,并在布局 xml 中使用该类名称。不是成员变量看起来你正在尝试做的事情。展开布局后,您可以使用以下方式访问自定义视图:

org.me.myapp.MyView myView = (org.me.myapp.MyView) findViewById(R.id.MYVIEWID);

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 myView = (org.me.myapp.MyView) findViewById(R.id.MYVIEWID);
断肠人 2024-11-05 06:30:47

我认为您需要将自定义布局声明为单独的类,例如: org.me.myapp.MyView 并在 xml 文件中将其关联起来,如下所示:

<org.me.myapp.MyView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  ...
/>

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:

<org.me.myapp.MyView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  ...
/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文