5

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

package com.my.android.library.layout;

public class CustomView extends View {
...

我还为我定义了 styleableCustomView

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

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

接下来,我制作了一个使用分布式库项目的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)

似乎它不能膨胀 my CustomViewin layout xml。为什么?如何摆脱它?

(我检查了主库jar文件,有CustomView类。请不要随便给我一个Android网站的链接而不解释。)

4

2 回答 2

1

由于您是从 jar 中添加视图,因此您应该能够将命名空间指定为:

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

其中“root_package_name”可以是“com.my.android.library.layout”或“com.my.android.library”或类似的东西。

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

Android Activity ClassNotFoundException - 尝试了一切

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

ClassNotFoundException:找不到类“com.google.android.gms.ads.AdView”

于 2014-08-13T13:26:26.217 回答
-1

让我们尝试这样做:

  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
  }

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

于 2014-08-07T11:56:24.680 回答