I am working on the quiz application
.For that I am using listview for the dispaly the answers options
, I want to change the listview background col
Do you want to change the background of listview or the selected item when a correct answer is selected.
@Override
public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {
String selectedFromList = (String) listview.getItemAtPosition(pos);
if(selectedFromList.equals("your_answer")) {
// to change the listview background
listview.setBackgroundColor(getResources().getColor(R.color.your_color_id));
// to change the selected item background color
myView.setBackgroundColor(getResources().getColor(R.color.your_color_id));
}
I would suggest to go with the following way: Adapter class: add storing of selected position and its state (CORRECT/INCORRECT) or color, e.g.:
public class ListviewAdapter extends BaseAdapter{
enum AnswerStates {
// Colors can be provided also for bg
WRONG(R.drawable.wrong_bg),
RIGHT(R.drawable.right_bg),
NONE(R.drawable.list_item_bg);
/** Drawable id to be used for answer state */
private int mBg;
private AnswerStates(int bg) {
mBg = bg;
}
/** getter for drawabale for answer state */
int getBg() {
return mBg;
}
}
...
/** Position of selected answer */
private int mSelectedPosition = -1;
/** State of selected answer */
private AnswerStates mSelectedAnswerState = AnswerStates.NONE;
...
/** Setter for selected answer */
public void setSelectedAnswerState(int selectedPosition, AnswerStates state) {
mSelectedPosition = selectedPosition;
mSelectedAnswerState = state;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
// Your stuff
...
if (position == mSelectedPosition) {
convertView.setBackgroundResource(mSelectedAnswerState.getBg());
} else {
// use default bg
convertView.setBackgroundResource(AnswerStates.NONE.getBg());
}
return convertView;
}
...
}
And Activity class:
public class Display_questions extends Activity{
...
// Added position parameter to the function
static boolean checkAnswer(int selectedPosition) {
//getSelectedAnswer();
String answer = SelectedAnswer.getAnswer();
if (answer==null){
return false;
}
else {
AnswerStates state = AnswerStates.NONE;
if (currentQ.getAnswer().trim().equals(answer.trim()))
{
// here set the background Green color
currentGame.incrementRightAnswers();
state = AnswerStates.RIGHT;
}
else{
// here set the background red color
//ListviewAdapter.setbackground();
currentGame.incrementWrongAnswers();
state = AnswerStates.WRONG;
}
adapter.setSelectedAnswerState(selectedPosition, state);
adapter.notifyDataSetChanged();
return true;
}
}
}
This way is more reliable than another answer, because it will work even if list with answers get scrolled and views get reused by list view.