【问题标题】:view.findViewById returns null for ImageView but not ListViewview.findViewById 为 ImageView 返回 null 而不是 ListView
【发布时间】:2023-03-25 09:21:02
【问题描述】:

在我的片段中使用view.findViewById(id) 来查找ListView 时,返回正常,我可以使用该值,但是,当我尝试使用完全相同的方法查找ImageView 时,只是将ID 更改为正确的,它将返回 null,这会导致应用程序稍后出现问题。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View fragmentView = inflater.inflate(R.layout.fragment_boardlist,
                container, false);

        boardListView = (ListView) fragmentView
                .findViewById(R.id.fragmentListView);
        stickyImageView = (ImageView) fragmentView
                .findViewById(R.id.favouriteImageView);

            // ...          

        return fragmentView;
    }

不知道为什么会发生这种情况,因为我正在使用相同的方式,所以我想知道是否有其他人知道原因。

这是 XML:

<TextView
    android:id="@+id/initialsTextView"
    android:layout_width="35dp"
    android:layout_height="fill_parent"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:gravity="center_vertical"
    android:textSize="12sp" />

<TextView
    android:id="@+id/fullNameTextView"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:layout_weight=".85"
    android:gravity="center_vertical"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView
    android:id="@+id/favouriteImageView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight=".15"
    android:clickable="true"
    android:contentDescription="@string/imageview_contentdescription"
    android:src="@android:drawable/star_big_off" />

【问题讨论】:

  • 能贴出ImageView所在的xml吗?
  • @E.Odebugg,当然。我已将其添加到问题中。
  • 您是否忘记复制 XML 文件的 ListView 部分?
  • @dymmeh ListView 在片段本身中,这是自定义 ListView 行的 XML。
  • 您正在为单个列表行加载整个片段?要从 ListFragment 中获取 ListView,只需调用 getListView()。

标签: android android-listview android-imageview


【解决方案1】:

如果我错了,请纠正我,但如果您尝试访问属于 ListView 自定义行的一部分的 ImageView,首先您需要设置适配器。然后,您需要从 Adapter 覆盖 getView()。然后获取 ImageView 的引用。

【讨论】:

  • 是的,ImageView 是自定义行的一部分。我设置了使用 getView() 工作的适配器,数据将在应用程序上正确填充,但在我的片段中,我试图为 ImageView 设置一个侦听器,以便用户可以将该行切换为收藏夹。跨度>
  • 啊,我刚刚想通了。我试图将听众放在现在我仔细考虑过的片段中,这是愚蠢的。我只需要在适配器的getView() 方法中设置监听器即可。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多