我正在构建一个Android应用程序。在我的主要活动中,我有一个FragmentPageAdpater
,我基本上做的是我有一个可重用的Fragment类,我示例化了三次。
我的片段包含三个不同“页面”的数据,我使用操作栏中当前的“活动选项卡”来确定和过滤应该向用户显示的数据,数据基本上是一个列表(狗、猫、鸟)并且用户可以选择品种。狗片段首先开始并且当用户选择一个时,我的应用程序突出显示选中的行,并继续到下一行(猫碎片)。2该过程重复,直到用户能够从所有三个类别中选择一个品种。
为了突出显示用户选择,我在ListView
中的onItemClickListener
中执行此操作
view.setBackgroundColor(Color.GREEN);
字符串
其中view
是onItemClickListener
函数中的View view
参数。
然而,发生的事情是,当我到鸟的片段,并选择然后滚动/滑动回到狗的片段,绿色突出消失。
我所做的尝试是用一个int来标记选择了哪个品种索引,然后在片段的onResume
上,获取适当的int标记,然后获取我的listView,获取该行的子元素,然后设置背景颜色。然而,我在代码块中遇到了一个NullPointerException,如下所示:
这是我在Fragment中的onResume函数:
@Override
public void onResume() {
super.onResume();
//I get my MainActivity/the base one, get the view pager, and get the current item
int index = ((MainActivity)getActivity()).mViewPager.getCurrentItem();
Log.d("hi", "index is = " + index);
switch(index){
case 0:
//dogSelected is the index of the selected item in the dogFragment
if(((MainActivity)getActivity()).dogSelected > -1){
Log.d("hi","selected dog = " + ((MainActivity)getActivity()).dogSelected);
//I reinitialize the listView
listViewBreeds = (ListView) rootView.findViewById(R.id.listViewBreeds);
adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DogBreeds);
//DogBreeds is an ArrayList of DogBreeds
listViewBreeds.setAdapter(adapter);
//check for null
if(listViewBreeds == null){
Log.d("hi", "hello, lvn NULL");
}
int pos = ((MainActivity)getActivity()).dogSelected; // + 1;
listViewBreeds.getChildAt(pos).setBackgroundColor(Color.GREEN);
}
break;
case 1:
//same as case 0
}
}
型
正如你在我的代码中看到的,在片段的onResume期间,我检查哪个片段索引是活动的,这样我就知道在我的switch-case语句中要查找哪个列表。记录的索引是正确的。然后根据索引,然后我查找我的列表和保存在基本活动中的索引。选择的狗(或猫)是正确的。之后我重新初始化listView以确保它不为空。(log语句不显示)。然后我得到listView,在选定的位置得到孩子,然后设置背景颜色。
然而,我在这行得到了一个NullPointer:
listViewBreeds.getChildAt(pos).setBackgroundColor(Color.GREEN);
型
我不知道哪部分是空的
1条答案
按热度按时间jutyujz01#
我实际上已经让它工作了。解决方案是使用CustomListView Adapter,然后为行条目创建一个对象。该对象具有布尔值
isSelected
,然后在Custom ListView Adapter中,背景设置为不同的颜色或设置回白色,具体取决于isSelected
变量。