Android -在Fragments onResume函数中设置listView的子元素的背景颜色会产生NullPointerException

pzfprimi  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(150)

我正在构建一个Android应用程序。在我的主要活动中,我有一个FragmentPageAdpater,我基本上做的是我有一个可重用的Fragment类,我示例化了三次。
我的片段包含三个不同“页面”的数据,我使用操作栏中当前的“活动选项卡”来确定和过滤应该向用户显示的数据,数据基本上是一个列表(狗、猫、鸟)并且用户可以选择品种。狗片段首先开始并且当用户选择一个时,我的应用程序突出显示选中的行,并继续到下一行(猫碎片)。2该过程重复,直到用户能够从所有三个类别中选择一个品种。
为了突出显示用户选择,我在ListView中的onItemClickListener中执行此操作

  1. view.setBackgroundColor(Color.GREEN);

字符串
其中viewonItemClickListener函数中的View view参数。
然而,发生的事情是,当我到鸟的片段,并选择然后滚动/滑动回到狗的片段,绿色突出消失。
我所做的尝试是用一个int来标记选择了哪个品种索引,然后在片段的onResume上,获取适当的int标记,然后获取我的listView,获取该行的子元素,然后设置背景颜色。然而,我在代码块中遇到了一个NullPointerException,如下所示:
这是我在Fragment中的onResume函数:

  1. @Override
  2. public void onResume() {
  3. super.onResume();
  4. //I get my MainActivity/the base one, get the view pager, and get the current item
  5. int index = ((MainActivity)getActivity()).mViewPager.getCurrentItem();
  6. Log.d("hi", "index is = " + index);
  7. switch(index){
  8. case 0:
  9. //dogSelected is the index of the selected item in the dogFragment
  10. if(((MainActivity)getActivity()).dogSelected > -1){
  11. Log.d("hi","selected dog = " + ((MainActivity)getActivity()).dogSelected);
  12. //I reinitialize the listView
  13. listViewBreeds = (ListView) rootView.findViewById(R.id.listViewBreeds);
  14. adapter = new ArrayAdapter<>(getActivity(),
  15. android.R.layout.simple_list_item_1, android.R.id.text1, DogBreeds);
  16. //DogBreeds is an ArrayList of DogBreeds
  17. listViewBreeds.setAdapter(adapter);
  18. //check for null
  19. if(listViewBreeds == null){
  20. Log.d("hi", "hello, lvn NULL");
  21. }
  22. int pos = ((MainActivity)getActivity()).dogSelected; // + 1;
  23. listViewBreeds.getChildAt(pos).setBackgroundColor(Color.GREEN);
  24. }
  25. break;
  26. case 1:
  27. //same as case 0
  28. }
  29. }


正如你在我的代码中看到的,在片段的onResume期间,我检查哪个片段索引是活动的,这样我就知道在我的switch-case语句中要查找哪个列表。记录的索引是正确的。然后根据索引,然后我查找我的列表和保存在基本活动中的索引。选择的狗(或猫)是正确的。之后我重新初始化listView以确保它不为空。(log语句不显示)。然后我得到listView,在选定的位置得到孩子,然后设置背景颜色。
然而,我在这行得到了一个NullPointer:

  1. listViewBreeds.getChildAt(pos).setBackgroundColor(Color.GREEN);


我不知道哪部分是空的

jutyujz0

jutyujz01#

我实际上已经让它工作了。解决方案是使用CustomListView Adapter,然后为行条目创建一个对象。该对象具有布尔值isSelected,然后在Custom ListView Adapter中,背景设置为不同的颜色或设置回白色,具体取决于isSelected变量。

相关问题