【问题标题】:How to use own view in layout?如何在布局中使用自己的视图?
【发布时间】:2011-07-27 17:20:41
【问题描述】:

我创建了一个这样的类

public final class MyView extends View {

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        [...]
    }
        [...]
}

然后我想在我的 layout.xml 中使用它

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent">

  <com.hitziger.barcode.MyView
      android:id="@+id/my_view"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>

</FrameLayout>

但是 Eclipse 在错误日志中告诉我

AndroidManifest:忽略未知 'com.hitziger.barcode.MyView' XML 元素

如何使 MyView 在布局中可访问?我必须在其他地方发布这个课程吗?

【问题讨论】:

  • 你能尝试重建你的项目并部署它吗?好像eclipse搞砸了……
  • 每次我遇到这种情况时,结果证明我输入了错误的包名或类名。您能否从 .java 文件、类声明以及引用该类的实际 XML 行中剪切并粘贴实际的包行?

标签: android xml layout view


【解决方案1】:

你应该这样写:

<view class="com.hitziger.barcode.MyView"...

【讨论】:

  • 如何在我的代码中访问它? myView = (MyView) findViewById(R.id.my_view);当我在模拟器上运行程序时,给了我一个关闭的力。
  • 查看 LogCat 错误消息并将其发布在此处。大多数时候,当您看到错误日志的内容时,您就可以解决自己的问题..
  • 简而言之,在您的活动中:setCotentView(R.layout.layout); MyView myView = (MyView)findViewById(R.layout.my_view); 在此处阅读更多信息:developer.android.com/guide/topics/ui/declaring-layout.html
【解决方案2】:

在 layout.xml 中,使用:

<View 
    android:class="com.hitziger.barcode.MyView"
    android:id="@+id/my_view"
...

代替:

<com.hitziger.barcode.MyView
    android:id="@+id/my_view"

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 2016-01-06
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多