在我的案例中使用库项目的自定义视图

时间:2014-08-07 10:46:02

标签: android android-layout android-custom-view android-library android-custom-attributes

我制作了一个Android 主库项目,其中我创建了一个自定义视图类:

package com.my.android.library.layout;

public class CustomView extends View {
...

我还为CustomView定义了样式

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <declare-styleable name="CustomView">
        <attr name="title_text" format="string" />
    </declare-styleable>
</resources>

由于我不想将我的源代码分享给正在使用我的库项目的其他人,所以我创建了一个分布式库项目,其中我添加了上面的jar 主库项目分布式库项目libs/文件夹,并将所有资源从主库项目复制到分布式库项目

NEXT,我创建了一个 Android应用程序项目,它使用分布式库项目。在app项目的主布局文件中,我定义了以下内容:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <com.my.android.library.layout.CustomView
        custom:title_text = "THIS IS TITLE" 
        />
<RelativeLayout>

当我运行我的应用程序时,我遇到以下异常:

E/AndroidRuntime(30993): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.android.app/com.my.android.app.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class com.my.android.library.layout.CustomView
E/AndroidRuntime(30993):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
E/AndroidRuntime(30993):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096)
    ...
   Caused by: java.lang.ClassNotFoundException: com.my.android.library.layout.CustomView
E/AndroidRuntime( 2947):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
E/AndroidRuntime( 2947):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
E/AndroidRuntime( 2947):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
E/AndroidRuntime( 2947):    at android.view.LayoutInflater.createView(LayoutInflater.java:552)
E/AndroidRuntime( 2947):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)

似乎无法在布局xml中夸大我的CustomView。为什么?如何摆脱它?

(我检查了主库jar文件,有CustomView课程。请不要向我提供Android网站的链接,不做任何解释。)

2 个答案:

答案 0 :(得分:1)

由于您要从jar添加View,因此您应该能够将命名空间指定为:

 xmlns:custom="http://schemas.android.com/apk/lib/root_package_name

where&#34; root_package_name&#34;可能是&#34; com.my.android.library.layout&#34;或&#34; com.my.android.library&#34;或类似的东西。

如果这不起作用,则可能是&#34;订购和导出&#34;问题或您添加库的方式。确保正确包含库:

Android Activity ClassNotFoundException - tried everything

最后,如果这也失败了,那么您可能需要更新Android SDK:

ClassNotFoundException: Didn't find class "com.google.android.gms.ads.AdView"

答案 1 :(得分:0)

让我们尝试这样做:

  public CustomView(Context context) {
    this(context, null, 0);
  }

  public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public CustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    //init your stuff here
  }

你能给我们完整的异常堆栈跟踪吗?