I want to color the item in the listview. When I clicked the item in listview the alert dialog shows then it colors the item if your click yes in the dialog using setChoiceMode multiple, The problem is whenever I click the item before the alert dialog shows the listview item already colored, Please check this out, I'm just a newbie in android thank you.
MainActivity.java
text_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
isSelected[position]=!isSelected[position];
alert_dialog();
}
});
}
public void alert_dialog(){
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure you want to color this item?")
.setMessage("Please Confirm")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
text_listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();
}
})
.show();
}
myselecter
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/lightOrange" android:state_activated="true"/>
</selector>
arrayadapter
ArrayList<String> list_items = new ArrayList<String>();
ArrayAdapter arrayAdapter;
private boolean[] isSelected; //declaration
arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
text_listview.setAdapter(arrayAdapter);
isSelected=new boolean[arrayAdapter.getCount()];
You are supposed to set the selection after clicking on yes in dailog. Modify your code like this.
text_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alert_dialog(position);
}
});
}
public void alert_dialog(final int position){
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure you want to color this item?")
.setMessage("Please Confirm")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
isSelected[position]=true;
text_listview.setItemChecked(position,true); //Setting selected state here
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
isSelected[position]=false;
text_listview.setItemChecked(position,false);
Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();
}
})
.show();
}