我已经成功实现了带有自定义适配器的列表视图,该适配器显示图片和标题。它还设置为多次单击视图,因此可以选择多个项目,并且数据可以传递到其他活动。我还实现了一项功能,以便当我单击某个项目时其背景会更改颜色。
我唯一无法解决的问题是,当我单击第二个项目时,第一个项目的背景色会变回原来的颜色。我希望所有单击的项目保持颜色不变。
// Assigns the listView variable to the listView in the xml file.
listView = findViewById(R.id.distortedListViewWorkout);
// Instantiate the Custom Adapter (currently not being used)
MyAdapter adapter = new MyAdapter(this, mTitle, images);
// Instantiates the Adatper with a premade android simple layout and the title array list.
listView.setAdapter(adapter);
//((new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, mTitle)));
// Enables the user to select multiple items in the listview.
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// sets an onItemClickListener for the listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**
*
* @param parent
* @param view
* @param position
* @param id
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// variable which will capture the title of the item selected in the listView.
distortionsString = "";
int userInput = listView.getCount();
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for(int loop = 0; loop < userInput; loop++){
if(sparseBooleanArray.get(loop)) {
distortionsString += listView.getItemAtPosition(loop).toString() + "\n";
view.setSelected(true);
}
}
}});
}
/**
* Custom Adapter class containing an icon and title.
*/
class MyAdapter extends ArrayAdapter<String> {
Context context;
String rTitle[];
int rImages[];
MyAdapter (Context c, String title[], int images[]){
super(c, R.layout.row, R.id.titleEtWorkout, title);
this.context = c;
this.rTitle = title;
this.rImages = images;
}
/**
*
* @param position
* @param convertView
* @param parent
* @return
*/
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.row, parent, false);
ImageView images = row.findViewById(R.id.iconsWorkout);
TextView myTitle = row.findViewById(R.id.titleEtWorkout);
images.setImageResource(rImages[position]);
myTitle.setText(rTitle[position]);
return row;
}
}
}