我正在构建一个 Android 应用程序。在我的主要活动中,我有一个
FragmentPageAdpater
,我基本上做的是我有这个可重用的 Fragment 类,我实例化了三次。
我的片段包含三个不同“页面”的数据。我使用操作栏中当前的“活动选项卡”来找出并过滤应该向用户显示哪些数据。数据基本上是一个列表(狗、猫、鸟),用户可以选择一个品种。狗片段首先开始,当用户选择一个片段时,我的应用程序会突出显示所选行并继续处理下一个片段(猫片段)。重复该过程,直到用户能够从所有三个类别中选择一个品种。
为了突出显示用户选择,我在我的
onItemClickListener
中执行此操作
ListView
其中 view.setBackgroundColor(Color.GREEN);
是 view
函数中的
View view
参数。
但是,当我到达鸟类片段并选择然后滚动/滑动回狗片段时,绿色突出显示消失。我所做的尝试是用一个 int 来标记选择了哪个品种索引,然后在 Fragment 的
onItemClickListener
这是我在 Fragment 中的 onResume 函数:
onResume
正如您在我的代码中看到的,在片段的 onResume 期间,我检查哪个片段索引处于活动状态,以便我知道要在 switch-case 语句中查找哪个列表。记录的索引是正确的。然后根据索引,我查找我的列表和基本活动中保存的索引。所选的狗(或猫)是正确的。之后,我重新初始化 listView 以确保它不为空(日志语句不显示)。然后我获取 listView,将子视图置于所选位置,然后设置背景颜色。但是,我在该行得到一个空指针:
@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
}
}
而且我不知道哪一部分是空的。
我实际上已经让它工作了。解决方案是使用 CustomListView 适配器,然后为行条目创建一个对象。该对象有一个布尔值
isSelected
变量将背景设置为不同的颜色或设置回白色。