【问题标题】:findViewById return null, when export a project to jar file and import it into my project将项目导出到 jar 文件并将其导入我的项目时,findViewById 返回 null
【发布时间】:2015-09-21 09:12:16
【问题描述】:

我将第三方项目导出为 jar 文件并将该项目设置为库,然后将其导入到我的项目中。文件夹布局下xml文件中的“@+id”全部修改为“@id”。我在第三方项目中添加了 ids.xml&public.xml 文件。 Mainifest.xml 也添加了。

在我的项目中,像it.setClass(this, ActivityImageDetail.class);这样的代码实际上运行到了ActivityImageDetail.class,这是jar文件中的第三方类。

但是当它执行 layout = (LinearLayout) findViewById(R.id.***); 时,我得到了 Null。

Logcat 说java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mytest/com.MobileVisualSearch.ActivityImageDetail}: java.lang.NullPointerException

看来第三方类中的所有findViewById()都返回null

我该如何解决?

【问题讨论】:

  • 您是否尝试过“清除项目”并重新创建 R.java ?

标签: android xml null findviewbyid


【解决方案1】:

遗憾的是,您不能使用 JAR 文件来存储 Android 资源。生成的R.java 不会包含来自 JAR 文件的信息。

【讨论】:

  • 我知道 R.id.** 将被编译到 JAR 中的 ID 值中,所以我在 3rd 方项目中添加了两个文件,就像我说的 ids.xml 和 public.xml。我的项目应该通过 ID 值找到这些 UI。
【解决方案2】:

你能把代码贴在下面一行吗?

layout = (LinearLayout) findViewById(R.id.***);

在尝试从中获取特定 id 之前,您是否对布局文件进行了扩充?

我做了一个小项目,它通过以下方式使用库中的布局:

View view = inflater.inflate(R.layout.imported_layout, container, false);
TextView textView = (TextView) view.findViewById(R.id.imported_textview);

textView.setText("Hey, I'm an imported TextView");

而imported_layout.xml只是一个非常简单的布局:

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

    <TextView
        android:id="@+id/imported_textview"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

</LinearLayout>

编辑:这是可能的,因为我已经导入了库项目,但我没有将它用作导入的 .jar。

【讨论】:

  • setContentView(R.layout.activityimagedetail);布局 = (LinearLayout) findViewById(R.id.activityimagedetail_linearlayout); ImageView imageView_TitleBar = (ImageView) findViewById(R.id.imageViewTitle_ImageDetail);布局和 ImageView 都是 NULL。上面的代码被导出到我的项目和第 3 方项目中使用的 Jar 文件作为库项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
相关资源
最近更新 更多