I have an issue while loading data in adapter view of recycle view.
I have two Fragment in activity and 2nd Fragment have 3 recycle views. But the problem is that I have a checkbox in raw view holder, I checked some one of that. when i scroll up /down then that data of recycleview data rearrange as default and all check boxes are again false.
I used set recycle(false) in on bind method but still not working.
public class VenueOrderPriceAdapter extends
RecyclerView.Adapter<VenueOrderPriceAdapter.DataViewHolder> {
static Context mContext;
public static double final_total;
public static String selected_hr,selected_min;
static private List<VenueOrderPriceModel> stList;
static private String str_id, str_charges, str_is_flat_charges, str_is_per_person_charges;
/*str_hour_extension_charges, str_extra_person_charges=null, str_is_group_size, str_group_size_from,
str_group_size_to*/;
private static boolean isPkgAdded;
public VenueOrderPriceAdapter(Context mContext, List<VenueOrderPriceModel> students) {
this.mContext = mContext;
this.stList = students;
}
// Create new views
#Override
public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_venueorder_price, parent,false);
Log.e("on create called---","dsdf--111");
// create ViewHolder
DataViewHolder viewHolder = new DataViewHolder(itemLayoutView);
final_total=0;
return viewHolder;
}
#Override
public void onBindViewHolder(final DataViewHolder viewHolder, final int positiona) {
Log.e("on bind called---","dsdf"+positiona);
viewHolder.setIsRecyclable(false);
}
// Return the size arraylist
#Override
public int getItemCount() {
return stList.size();
}
public static class DataViewHolder extends RecyclerView.ViewHolder {
public TextView tvName,tv_details,tv_duration ,tv_guestCount,tv_price,tv_extra_charge,tv_addtocart,tv_pkg_rate;
CheckBox cb_selectedprice;
private LinearLayout ll_extra,ll_extra_charge;
Spinner sp_hh,sp_mm,sp_qty;
ImageView img_clock,img_guest,img_remove;
public DataViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvName = (TextView) itemLayoutView.findViewById(R.id.tvName);
tv_details = (TextView) itemLayoutView.findViewById(R.id.tv_details);
tv_duration = (TextView) itemLayoutView.findViewById(R.id.tv_duration);
tv_guestCount = (TextView) itemLayoutView.findViewById(R.id.tv_guestCount);
tv_price = (TextView) itemLayoutView.findViewById(R.id.tv_price);
tv_extra_charge = (TextView)itemLayoutView.findViewById(R.id.tv_extra_charge);
tv_pkg_rate = (TextView)itemLayoutView.findViewById(R.id.tv_pkg_rate);
img_clock = (ImageView) itemLayoutView.findViewById(R.id.img_clock);
img_guest = (ImageView) itemLayoutView.findViewById(R.id.img_guest);
img_remove = (ImageView) itemLayoutView.findViewById(R.id.img_remove);
sp_hh = (Spinner)itemView.findViewById(R.id.sp_hh);
sp_mm = (Spinner)itemView.findViewById(R.id.sp_mm);
sp_qty = (Spinner)itemView.findViewById(R.id.sp_qty);
// tv_ext_person= (TextView)itemView.findViewById(R.id.tv_ext_person);
ll_extra =(LinearLayout)itemView.findViewById(R.id.ll_extra);
ll_extra_charge =(LinearLayout)itemView.findViewById(R.id.ll_extra_charge);
tv_addtocart= (TextView) itemView.findViewById(R.id.tv_addtocart);
cb_selectedprice =(CheckBox)itemView.findViewById(R.id.cb_selectedprice);
final int position = getAdapterPosition();
String extra_duration_charge = "";
str_id= stList.get(position).getId();
if(stList.get(position).getIs_applicable().equalsIgnoreCase("0")){
itemView.setEnabled(false);
itemView.setClickable(false);
itemView.setBackgroundResource(R.color.md_blue_grey_50);
tv_addtocart.setVisibility(View.GONE);
}
tvName.setText(stList.get(position).getPackage_name());
tv_details.setText(stList.get(position).getChrages_inclusion());
tv_price.setText(" $ "+Const.GLOBAL_FORMATTER.format(Double.parseDouble(stList.get(position).getCharges())));
if(stList.get(position).getPacakage_hours()!=null){
tv_duration.setText(stList.get(position).getPacakage_hours().substring(0,stList.get(position).getPacakage_hours().length()-3)+" hr");
}else{
tv_duration.setVisibility(View.GONE);
}
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1")){
tv_guestCount.setText(stList.get(position).getGroup_size_from()
+"-"
+stList.get(position).getGroup_size_to() +" Guest");
}else{
tv_guestCount.setVisibility(View.GONE);
}
//======EXTRA GUEST AND TIME CONDITION FOR TEXT VIEW ==========================================
if(stList.get(position).getIs_hour_extension_charges()!=null) {
if(stList.get(position).getIs_hour_extension_charges().equalsIgnoreCase("1")){
ll_extra_charge.setVisibility(View.VISIBLE);
if (stList.get(position).getExtension_hours().substring(0, 2).equalsIgnoreCase("00")) {
extra_duration_charge = "$ " + stList.get(position).getHour_extension_charges() + " / " + stList.get(position).getExtension_hours().substring(3, 5) + " min";
} else {
extra_duration_charge = "$ " + stList.get(position).getHour_extension_charges() + " / " + stList.get(position).getExtension_hours().substring(0, 5) + " hours";
}
tv_extra_charge.setText(extra_duration_charge);
}
}
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1") && stList.get(position).getIs_extra_person_charges().equalsIgnoreCase("1")){
extra_duration_charge = extra_duration_charge+"\n"+"$"+stList.get(position).getIs_extra_person_charges()+"/ person";
tv_extra_charge.setText(extra_duration_charge);
}
if(extra_duration_charge==null || extra_duration_charge.length()<1){
ll_extra_charge.setVisibility(View.GONE);
if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Flat Rate");
} else if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Per Person");
} else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")) {
tv_pkg_rate.setText("Per Hour");
}
}else{
if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Flat Rate");
} else if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Per Person");
} else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")) {
tv_pkg_rate.setText("Per Hour");
}
}
//==========FLAT PER PERSON PER HOURE CHARGES CONDITION======================================================
if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
ll_extra.setVisibility(View.INVISIBLE);
// tv_ext_person.setVisibility(View.GONE);
} else if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1") && stList.get(position).getExtra_person_charges()!=null){
ll_extra.setVisibility(View.VISIBLE);
img_clock.setVisibility(View.GONE);
sp_hh.setVisibility(View.GONE);
//np_itemcount.setVisibility(View.VISIBLE);
// tv_ext_person.setVisibility(View.VISIBLE);
//np_itemcount.setMaxValue(Integer.parseInt(stList.get(position).getGroup_size_to()));
}else{
ll_extra.setVisibility(View.INVISIBLE);
//tv_ext_person.setVisibility(View.GONE);
}
if(stList.get(position).getIs_extra_person_charges().equalsIgnoreCase("0")){
ll_extra.setVisibility(View.INVISIBLE);
//tv_ext_person.setVisibility(View.GONE);
}
}else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")) {
ll_extra.setVisibility(View.VISIBLE);
img_guest.setVisibility(View.GONE);
sp_qty.setVisibility(View.GONE);
//ll_duration.setVisibility(View.GONE);
}
List<String> list_hh = new ArrayList<String>();
list_hh.add("HH");
list_hh.add("01");
list_hh.add("02");
list_hh.add("03");
list_hh.add("04");
list_hh.add("05");
list_hh.add("06");
list_hh.add("07");
list_hh.add("08");
list_hh.add("09");
list_hh.add("10");
list_hh.add("11");
list_hh.add("12");
ArrayAdapter<String> dataAdapter_hh = new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, list_hh);
dataAdapter_hh.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_hh.setAdapter(dataAdapter_hh);
List<String> list_mm = new ArrayList<String>();
list_mm.add("MM");
list_mm.add("00");
list_mm.add("15");
list_mm.add("30");
list_mm.add("45");
ArrayAdapter<String> dataAdapter_mm = new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, list_mm);
dataAdapter_mm.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_mm.setAdapter(dataAdapter_mm);
List<String> list_qty = new ArrayList<String>();
list_qty.add("Guest");
for(int a=0;a<100;a++){
list_qty.add(Integer.toString(a));
}
ArrayAdapter<String> dataAdapter_qty = new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, list_qty);
dataAdapter_qty.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_qty.setAdapter(dataAdapter_qty);
sp_hh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int positionSP, long id) {
if(sp_mm.getSelectedItemPosition()>1 && positionSP>1){
final_total = Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) * (double) (sp_hh.getSelectedItemPosition() +1) );
}else{
if(positionSP > 1) {
final_total = Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) * (double) (sp_hh.getSelectedItemPosition()));
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
}
}
/* Toast.makeText(parent.getContext(), "Time : " +
sp_hh.getItemAtPosition(sp_hh.getSelectedItemPosition()).toString()
+ ":"
+String.valueOf(sp_mm.getSelectedItem()), Toast.LENGTH_SHORT).show();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
sp_mm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int positionSP, long id) {
if(positionSP>1){
final_total = Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) *(double) (sp_hh.getSelectedItemPosition() + 1 ));
// tv_menutitle_venuepricing.setText("Pricing Plans "+" ( Total : "+final_total+" )");
}else{
if(sp_hh.getSelectedItemPosition()>0){
final_total =Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) * (double) (sp_hh.getSelectedItemPosition()));
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
}
}
/*Toast.makeText(parent.getContext(), "Time : " + sp_hh.getItemAtPosition(sp_hh.getSelectedItemPosition()).toString()
+ ":" +sp_mm.getItemAtPosition(sp_mm.getSelectedItemPosition()).toString(), Toast.LENGTH_SHORT).show();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/*chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(chkSelected.isChecked()==true){
checked_count=checked_count+1;
if(checked_count > 1){
chkSelected.setChecked(false);
checked_count=checked_count-1;
Log.d("chk count ",""+checked_count);
}else {
Log.d("chk count",""+checked_count);
if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
final_total = Double.parseDouble(stList.get(position).getCharges()) * Double.parseDouble(et_guestCount.getText().toString());
// tv_menutitle_venuepricing.setText("Pricing Plans "+" ( Total : "+final_total+" )");
}else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")){
if(np_minutes_venue_pkg.getValue()>0){
final_total = Double.parseDouble(stList.get(position).getCharges()) * (double)(np_hour_venue_pkg.getValue()+1);
// tv_menutitle_venuepricing.setText("Pricing Plans "+" ( Total : "+final_total+" )");
}else{
if(np_hour_venue_pkg.getValue()>0) {
final_total = Double.parseDouble(stList.get(position).getCharges()) * (double) (np_hour_venue_pkg.getValue());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
//tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}
}
selected_hr= Integer.toString(np_hour_venue_pkg.getValue());
if(selected_hr.length()<=1){
selected_hr="0"+selected_hr;
}
selected_min=Integer.toString(np_minutes_venue_pkg.getValue());
if(selected_min.length()<=1){
selected_min="0"+selected_min;
}
}else if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1") && stList.get(position).getIs_extra_person_charges().equalsIgnoreCase("1") ){
int guest_from =Integer.parseInt(stList.get(position).getGroup_size_from());
int guest_to =Integer.parseInt(stList.get(position).getGroup_size_to());
int guest =Integer.parseInt(et_guestCount.getText().toString());
if(guest>guest_to){
int extra_guest = guest-guest_to;
final_total = ((double)extra_guest * Double.parseDouble(stList.get(position).getExtra_person_charges()) )
+Double.parseDouble(stList.get(position).getCharges());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : " + Const.GLOBAL_FORMATTER.format(final_total) + " )");
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}
}else {
final_total = Double.parseDouble(stList.get(position).getCharges());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}
}
}
}else{
checked_count=checked_count-1;
Log.d("chk count",""+checked_count);
if(checked_count==0){
// tv_menutitle_venuepricing.setText("Pricing Plans ");
}
}
VenueOrderPriceModel contact = (VenueOrderPriceModel) chkSelected.getTag();
contact.setSelected(chkSelected.isChecked());
stList.get(getAdapterPosition()).setSelected(chkSelected.isChecked());
*//*Toast.makeText(
chkSelected.getContext(),
"Clicked on Checkbox: " + chkSelected.getText() + " is "
+ chkSelected.isChecked(), Toast.LENGTH_LONG).show();*//*
}
});*/
if (cb_selectedprice.isChecked()==true){
img_remove.setVisibility(View.VISIBLE);
}else{
img_remove.setVisibility(View.GONE);
}
img_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isPkgAdded=false;
cb_selectedprice.setChecked(false);
img_remove.setVisibility(View.GONE);
tv_addtocart.setBackground(mContext.getResources().getDrawable(R.drawable.rounded_corner_orange_white_borde,mContext.getTheme()));
tv_addtocart.setEnabled(true);
final_total=0;
}
});
tv_addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPkgAdded == true || cb_selectedprice.isChecked()==true) {
Toast.makeText(mContext, "First Remove Added Pacakge", Toast.LENGTH_LONG).show();
} else {
Log.e("boooking details --",str_dateselected+str_guest_count+str_timeslot);
}
}
});
}
}
// method to access in activity after updating selection
public List<VenueOrderPriceModel> getStudentist() {
return stList;
}
}
You have to maintain the state of each checkbox in you data model from onCheckChangeListener of checkbox wrt every positions.
Then you have to set the checkbox state in onBind method of adapter
The recycler view recycles the view in OnBindViewHolder. So when items are scrolled view is recycled again.To solve this.
create a global variable to store the clicked position.
private mItemSelected=-1;
Then inside viewholder add the clickListener and onClick store the position of the clicked item.
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mItemSelected = getAdapterPosition();
notifyDataSetChanged();
}
});
}
}
And in inside OnBindViewHolder,
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(mItemSelected==position){
holder.status.setChecked(true);
}else{
holder.status.setChecked(false);
}
}
Related
I have a problem refreshing the cardviews in a listview after deleting or editing one cardview, I have tried with the .notifyDataSetChanged() but didn't work. I'm really new in Android Studio.
Here is my code:
RegistroActivity
public class RegistroActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private List<Registro> items = new ArrayList<>();
private RegistroAdapter registroAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
RegistroModel registroModel = new RegistroModel();
Cursor query = registroModel.showReg(HomeActivity.database);
if (query.moveToFirst()) {
do {
Registro expense = new Registro(query.getInt(0), query.getString(1), query.getFloat(2), query.getFloat(3), query.getString(4), query.getString(5) );
items.add(expense);
} while (query.moveToNext());
}
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setPadding(8, 8, 8, 8);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RegistroAdapter(items);
recyclerView.setAdapter(adapter);
}
}
I fill the data from a model with a simple select * from, and send the data to the adapter. Here is my adapter:
public class RegistroAdapter extends RecyclerView.Adapter<RegistroAdapter.RegistroViewHolder> {
private List<Registro> items;
public static class RegistroViewHolder extends RecyclerView.ViewHolder {
public ImageView color;
public TextView descr;
public TextView precio;
public TextView cantidad;
public ImageButton delete_expense;
public ImageButton edit_expense;
public Context cont;
public RegistroViewHolder(View v, Context context) {
super(v);
color = (ImageView) v.findViewById(R.id.card_image);
descr = (TextView) v.findViewById(R.id.description);
precio = (TextView) v.findViewById(R.id.precio);
cantidad = (TextView) v.findViewById(R.id.cantidad);
delete_expense = (ImageButton) v.findViewById(R.id.delete_button);
edit_expense = (ImageButton) v.findViewById(R.id.edit_button);
cont = context;
}
}
public RegistroAdapter(List<Registro> items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public RegistroViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.registro_card, viewGroup, false);
return new RegistroViewHolder(v, viewGroup.getContext());
}
//
#Override
public void onBindViewHolder(RegistroViewHolder viewHolder, final int i) {
String gramos = viewHolder.cont.getResources().getString(R.string.gramos);
String fecha = viewHolder.cont.getResources().getString(R.string.fecha);
String desc = viewHolder.cont.getResources().getString(R.string.tvDesc);
viewHolder.color.setImageResource(R.color.fondoCard);
viewHolder.descr.setText(fecha + " " + items.get(i).getDate() + "\n" + "\n" + " " + items.get(i).getDesc());
viewHolder.precio.setText(items.get(i).getPrice().toString() + " " + items.get(i).getMoneda() );
viewHolder.cantidad.setText(items.get(i).getAmount().toString() + " " + gramos );
viewHolder.edit_expense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), EditRegistroActivity.class);
int pos = items.get(i).getId();
intent.putExtra("position", pos);
v.getContext().startActivity(intent);
}
});
viewHolder.delete_expense.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = items.get(i).getId();
try{
SQLiteDatabase conn = HomeActivity.database.getWritableDatabase();
int n = conn.delete("registro","id="+pos, null);
if (n == 1){
Toast.makeText(v.getContext(), v.getContext().getString(R.string.mensajeEliminarexito), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(v.getContext(),v.getContext().getString(R.string.mensajeErrorEliminar) , Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(v.getContext(), "Error. ID=" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
I set the data within the elements in the card-view, this card-view has two Image-buttons to delete and edit each item in the card-view. I set the onClickListener for them. It edits and deletes completely fine but it doesn't refresh the information.
The reason is that you are making any changes on SQLite db and not in the adapter's items List. Adapter works only with the dataset you have passed to it when initializing it in your RegistroActivity. Therefore, when you want to change something you need to change SQLite to store modification permanently and refresh the dataset in adapters to allow user see the changes.
In your case, try adding three lines of code that are given below:
viewHolder.delete_expense.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = items.get(i).getId();
try{
SQLiteDatabase conn = HomeActivity.database.getWritableDatabase();
int n = conn.delete("registro","id="+pos, null);
items.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, item.size());
if (n == 1){
Toast.makeText(v.getContext(), v.getContext().getString(R.string.mensajeEliminarexito), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(v.getContext(),v.getContext().getString(R.string.mensajeErrorEliminar) , Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(v.getContext(), "Error. ID=" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
Just remove your item from adapter before notifying, like this
items.remove(i);
When you remove item from db it will not update you list, because your adapter holds data from passed before list.
I am using a cardstack through an array adapter. I am using getter setters to display the data on the card. But I am also getting back the duration of a the song that is associated with the card with getSongDuration(). The problem is when this loads and in the getView method i do:
songDuration = item.getSongDuration();
and log the value, it is being called multiple times for different positions.
I need to get the value for the song duration for the current song. Normally I would use the notify dataset changed but for this instance I do not see how that applies.
This is my adapter:
public class SongPreviewCardsDataAdapter extends ArrayAdapter<SongDatabaseMappingAdapter> {
private Context mContext;
public SongPreviewCardsDataAdapter(Context context, int resource) {
super(context, resource);
mContext = context;
}
ImageButton oneStarRating;
ImageButton twoStarRating;
ImageButton threeStarRating;
ImageButton fourStarRating;
ImageButton fiveStarRating;
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, final View contentView, ViewGroup parent) {
// Initialise Song Views
final SongDatabaseMappingAdapter item = getItem(position);
long songDuration = item.getSongDuration();
Log.d ("Duration", ""+songDuration);
TextView songName = (TextView) (contentView.findViewById(R.id.songNameTextView));
TextView artist_albumName = (TextView) (contentView.findViewById(R.id.artist_albumView));
com.mikhaellopez.circularimageview.CircularImageView songImage = (CircularImageView) contentView.findViewById(R.id.songImageView);
String ImageURL = (item.getPictureURL());
Picasso
.with(this.getContext())
.load(ImageURL)
.into(songImage);
final CircularProgressBar circularProgressBar = (CircularProgressBar)contentView.findViewById(R.id.songProgresswheel);
circularProgressBar.setColor(ContextCompat.getColor(getContext(), R.color.darkRed));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.darkBlueGrey));
circularProgressBar.setProgressBarWidth(10);
circularProgressBar.setBackgroundProgressBarWidth(10);
com.mikhaellopez.circularimageview.CircularImageView imagelocked = (CircularImageView) contentView.findViewById(R.id.lockedImageView);
// Initialise Rating Buttons
oneStarRating = (ImageButton) contentView.findViewById(R.id.ratingButton1);
twoStarRating = (ImageButton) contentView.findViewById(R.id.ratingButton2);
threeStarRating = (ImageButton) contentView.findViewById(R.id.ratingButton3);
fourStarRating = (ImageButton) contentView.findViewById(R.id.ratingButton4);
fiveStarRating = (ImageButton) contentView.findViewById(R.id.ratingButton5);
if (item.getOneStarRating()) {
oneStarRating.setImageResource(R.drawable.starfullnew);
imagelocked.setVisibility(contentView.GONE);
artist_albumName.setText(item.getArtist() + " - " + item.getAlbumTitle());
songName.setText(item.getSongTitle());
oneStarRating.setClickable(false);
twoStarRating.setClickable(false);
threeStarRating.setClickable(false);
fourStarRating.setClickable(false);
fiveStarRating.setClickable(false);
}
if (item.getTwoStarRating()) {
oneStarRating.setImageResource(R.drawable.starfullnew);
twoStarRating.setImageResource(R.drawable.starfullnew);
imagelocked.setVisibility(contentView.GONE);
artist_albumName.setText(item.getArtist() + " - " + item.getAlbumTitle());
songName.setText(item.getSongTitle());
oneStarRating.setClickable(false);
twoStarRating.setClickable(false);
threeStarRating.setClickable(false);
fourStarRating.setClickable(false);
fiveStarRating.setClickable(false);
}
if (item.getThreeStarRating()) {
oneStarRating.setImageResource(R.drawable.starfullnew);
twoStarRating.setImageResource(R.drawable.starfullnew);
threeStarRating.setImageResource(R.drawable.starfullnew);
imagelocked.setVisibility(contentView.GONE);
artist_albumName.setText(item.getArtist() + " - " + item.getAlbumTitle());
songName.setText(item.getSongTitle());
oneStarRating.setClickable(false);
twoStarRating.setClickable(false);
threeStarRating.setClickable(false);
fourStarRating.setClickable(false);
fiveStarRating.setClickable(false);
}
if (item.getFourStarRating()) {
oneStarRating.setImageResource(R.drawable.starfullnew);
twoStarRating.setImageResource(R.drawable.starfullnew);
threeStarRating.setImageResource(R.drawable.starfullnew);
fourStarRating.setImageResource(R.drawable.starfullnew);
imagelocked.setVisibility(contentView.GONE);
artist_albumName.setText(item.getArtist() + " - " + item.getAlbumTitle());
oneStarRating.setClickable(false);
twoStarRating.setClickable(false);
threeStarRating.setClickable(false);
fourStarRating.setClickable(false);
fiveStarRating.setClickable(false);
}
if (item.getFiveStarRating()) {
oneStarRating.setImageResource(R.drawable.starfullnew);
twoStarRating.setImageResource(R.drawable.starfullnew);
threeStarRating.setImageResource(R.drawable.starfullnew);
fourStarRating.setImageResource(R.drawable.starfullnew);
fiveStarRating.setImageResource(R.drawable.starfullnew);
imagelocked.setVisibility(contentView.GONE);
artist_albumName.setText(item.getArtist() + " - " + item.getAlbumTitle());
songName.setText(item.getSongTitle());
oneStarRating.setEnabled(false);
twoStarRating.setEnabled(false);
threeStarRating.setEnabled(false);
fourStarRating.setEnabled(false);
fiveStarRating.setEnabled(false);
}
oneStarRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Star", "Star Clicked");
item.setOneStarRating(true);
notifyDataSetChanged();
}
});
twoStarRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Star", "Star Clicked");
item.setTwoStarRating(true);
notifyDataSetChanged();
DemoPreviewSongFragment.userHasRatedSong = true;
}
});
threeStarRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Star", "Star Clicked");
item.setThreeStarRating(true);
notifyDataSetChanged();
DemoPreviewSongFragment.userHasRatedSong = true;
}
});
fourStarRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Star", "Star Clicked");
item.setFourStarRating(true);
notifyDataSetChanged();
DemoPreviewSongFragment.userHasRatedSong = true;
}
});
fiveStarRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Star", "Star Clicked");
item.setFiveStarRating(true);
notifyDataSetChanged();
DemoPreviewSongFragment.userHasRatedSong = true;
}
});
return contentView;
}
}
I want to implement the reclyerview to behave like following
items by default will be grey color and the other button hidden until on button add click:
The expansion happens one item per list if any other item is expanded clicking on the next item will first close any open item and then open the new one:
I have tried to implement it but every time a single item clicked and the expansion occurs, then no other item in the list will expand even though clicking on the plus button increases the number on it.
Also the expansion can appear on all items while on the reference its only one item per click that expands.
Here is my code
public class SalesProductsAdapter extends
RecyclerView.Adapter<SalesProductsAdapter.Vh>
implements
TextWatcher,Filterable,View.OnClickListener,AdapterView.OnItemClickListener
{
public List<SalesProductsItems> mItems = new ArrayList<SalesProductsItems>();
public static List<SalesProductsItems> filteredIt = new ArrayList<SalesProductsItems>();
#Override
public Vh onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.selling_screen_sellitems, parent, false);
Vh vh = new Vh(v);
return vh;
}
#Override
public void onBindViewHolder(final Vh holder, final int position) {
final SalesProductsItems cl = filteredIt.get(position);
if(pitems != null && pitems.size() > 0){
for(int j = 0; j < pitems.size(); j++){
Pending_Items _pitems = pitems.get(j);
long proid = cl.getProdid();
long _proid = _pitems.getProdloc();
if(proid == _proid){
prodname = cl.getProduct();
qty[0] = new BigDecimal(_pitems.getQty()).intValue();
unit[0] = _pitems.getPrice();
} else {
prodname = cl.getProduct();
qty[0] = new BigDecimal(cl.getQuantity()).intValue();
unit[0] = cl.getUnit();
}
}
} else {
prodname = cl.getProduct();
qty[0] = new BigDecimal(cl.getQuantity()).intValue();
unit[0] = cl.getUnit();
}
items = pitems.size();
if(items > 0)
imgnext.setVisibility(View.VISIBLE);
else
imgnext.setVisibility(View.GONE);
holder.txtproduct.setText(prodname);
updateViews(qty[0], holder);
if(qty[0] > 0){
System.out.println(" qty is " + s_qty);
holder.imgminus.setVisibility(View.GONE);
holder.imgadd.setVisibility(View.GONE);
holder.txtqty.setText(s_qty[0]);
holder.txtunit.setText(s_unit);
holder.txtsubtotal.setText(s_subtotal[0]);
} else {
holder.imgminus.setVisibility(View.GONE);
holder.txtqty.setVisibility(View.GONE);
holder.txtunit.setText(s_unit);
holder.txtsubtotal.setVisibility(View.GONE);
}
holder.imgadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
qty[0] += 1;
if(Products.checkQty(context,cl.getProdid(),qty[0])) {
if (qty[0] == 1) {
s_qty[0] = String.valueOf(qty[0]);
holder.txtqty.setText(s_qty[0]);
holder.txtqty.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
process_item(cl, holder,position);
changeBg(holder,qty[0]);
holder.txtsubtotal.setVisibility(View.VISIBLE);
} else {
s_qty[0] = String.valueOf(qty[0]);
holder.txtqty.setText(s_qty[0]);
process_item(cl, holder,position);
holder.txtsubtotal.setVisibility(View.VISIBLE);
}
} else {
Toast.makeText(context,cl.getProduct() + " " + context.getResources().getString(R.string
.strsalesquantityerror1) +
" " + Products.getItemOnHand(context,String.valueOf(cl.getProdid())) + " " + context.getResources()
.getString(R.string.strsalesquantityerror2), Toast.LENGTH_LONG).show();
}
}
});
holder.layview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.imgminus.getVisibility() == View.VISIBLE){
holder.imgminus.setVisibility(View.GONE);
if(qty[0] == 0) {
holder.imgadd.setVisibility(View.VISIBLE);
holder.txtqty.setVisibility(View.GONE);
}
else {
holder.txtqty.setVisibility(View.VISIBLE);
holder.imgadd.setVisibility(View.GONE);
holder.txtqty.setText(s_qty[0]);
}
} else {
Intent intent = new Intent(context,SingeItem.class);
intent.putExtra(Constants.SOURCE,Constants.SALETYPE_SALE);
intent.putExtra(Products.PRODUCTNAME,cl.getProdid());
intent.putExtra(Products.ID, position);
context.startActivity(intent);
}
}
});
holder.txtqty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.imgadd.getVisibility() == View.GONE){
holder.txtqty.setText(s_qty[0]);
holder.imgadd.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return filteredIt.size();
}
#Override
public long getItemId(int arg0){
return 0;
}
private void updateViews(int qt, Vh holder){
double un = unit[0];
double st = new BigDecimal(qt).multiply(new BigDecimal(un)).doubleValue();
s_qty[0] = String.valueOf(qt);
s_subtotal[0] = new BigDecimal(st).setScale(2, RoundingMode.HALF_UP).toString();
s_subtotal[0] = currency + " " + new BigDecimal(subtotal[0]).setScale(2, RoundingMode.HALF_UP).toString();
s_unit = currency+" "+new BigDecimal(unit[0]).setScale(2, RoundingMode.HALF_UP).toString();
holder.txtsubtotal.setText(s_subtotal[0]);
holder.txtunit.setText(s_unit);
holder.txtsubtotal.setVisibility(View.VISIBLE);
if(qt > 0)
imgnext.setVisibility(View.VISIBLE);
else
imgnext.setVisibility(View.GONE);
gtotal += subtotal[0];
txtt.setText(currency + " " + new BigDecimal(gtotal).setScale(2, RoundingMode.HALF_UP).toString());
txti.setText("/ " + items + " " + context.getString(R.string.stritems));
}
}
1) At a time if you want to show/hide only one element this one work fine
Step1)
create a variable and set its value to=-1;
int currentPosition=-1;
Step2)
On bind viewHolder,on itemClick update currentPosition to holder position
onBindViewHolder(ViewHolder v,int position)
{
view.Onclick(...{currentPosition=position;});
if(currentPosition==position)
view.setVisiblity(Visible);
else
view.setVisibility(Gone);
}
2) If you want to show more item on any button click then
Create 2 arrayList,first arrayList store total value and second
arrayList display only few elements in holder;
now on button click add all element to other arrayList and notify.
I am working on custom adapter. I created separate class for it which extends BaseAdapter. I am having two images - (minus) and + (plus) which will decrease or increase quantity of product in list view.
List item looks like
[ - Product qty + ]
Now I already implemented listener for - (minus) image and it is working. But listener for + (plus) image is not working. I printed qty on the console it is incrementing but not getting updated in listview.
Here is the code
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row_sold_item, null);
TextView txtListItem = (TextView) vi.findViewById(R.id.txtListItem);
txtQuantity = (TextView) vi.findViewById(R.id.txtQuantity);
ImageView imgCancel = (ImageView) vi.findViewById(R.id.imgCancel);
ImageView imgPlus = (ImageView) vi.findViewById(R.id.imgPlus);
HashMap<String, String> mapData = new HashMap<String, String>();
mapData = data.get(position);
txtListItem.setText(mapData.get("product"));
txtQuantity.setText(mapData.get("qty"));
imgCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doButtonOneClickActions(position);
}
});
imgPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qtyClickAction(position);
}
});
return vi;
}
private void qtyClickAction(int rowNumber) {
System.out.println(rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
System.out.println("before : " + qty);
qty++;
txtQuantity.setText("" + qty);
System.out.println("after : " + qty);
notifyDataSetChanged();
}
private void doButtonOneClickActions(int rowNumber) {
// Do the actions for Button one in row rowNumber (starts at zero)
System.out.println("rowNumber : " + rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
if (qty == 1) {
data.remove(rowNumber);
} else {
txtQuantity.setText("" + --qty);
}
notifyDataSetChanged();
}
One more thing, if I delete item in list, it is getting deleted. But how can I get notification for deleted item in my main class. Consider I selected 3 items, now I removed any one item by clicking - (minus). The item is getting deleted from list - the code is in adapter class
notifyDataSetChanged();
But how can I update total amount which is getting calculated in main class
try this it may help you,
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row_sold_item, null);
TextView txtListItem = (TextView) vi.findViewById(R.id.txtListItem);
TextView txtQuantity = (TextView) vi.findViewById(R.id.txtQuantity);
ImageView imgCancel = (ImageView) vi.findViewById(R.id.imgCancel);
ImageView imgPlus = (ImageView) vi.findViewById(R.id.imgPlus);
HashMap<String, String> mapData = new HashMap<String, String>();
mapData = data.get(position);
txtListItem.setText(mapData.get("product"));
txtQuantity.setText(mapData.get("qty"));
imgCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doButtonOneClickActions(txtQuantity,position);
}
});
imgPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qtyClickAction(txtQuantity,position);
}
});
return vi;
}
private void qtyClickAction(TextView txtQuantity,int rowNumber) {
System.out.println(rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
System.out.println("before : " + qty);
qty++;
txtQuantity.setText("" + qty);
System.out.println("after : " + qty);
}
private void doButtonOneClickActions(TextView txtQuantity,int rowNumber) {
// Do the actions for Button one in row rowNumber (starts at zero)
System.out.println("rowNumber : " + rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
if (qty == 1) {
data.remove(rowNumber);
notifyDataSetChanged();
} else {
txtQuantity.setText("" + --qty);
}
}
try this:
private void qtyClickAction(TextView txtQuantity,int rowNumber) {
System.out.println(rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
System.out.println("before : " + qty);
qty++;
data.get(rowNumber).set("qty")=qty;
//txtQuantity.setText("" + qty); not needed anymore
System.out.println("after : " + qty);
notifyDataSetChanged();
}
indeed you have not updated the data model so notifyDataSetChanged(); dose not take effect.
In order to send back updated data:
imgCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doButtonOneClickActions(position);
// update totalAmount
txtAmountAdapter.setText(Integer.valueOf(totalAmount).toString()));
}
});
imgPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qtyClickAction(position);
// update totalQty
txtAmountAdapter.setText(Integer.valueOf(totalAmount).toString()));
}
});
and pass txtAmount to the constructor of your adapter and store it as txtAmountAdapter. now every update in total amount update txtAmount in main.
i want the same as this link https://www.gorecess.com/ first spinner . multi selection spinner in android with checkbox .Show the spinner in dropdown. anyone know answer...
multi select spinner :
1- create a spinner in your own xml ,like this
<Spinner
android:id="#+id/mySpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="1dp"/>
2-create a custom dapter for spinner like this :
public class AdapterTagSpinnerItem extends ArrayAdapter<TagListSimpleSearch>
{
private LayoutInflater mInflater;
private List<TagListSimpleSearch> listState;
public Spinner mySpinner = null;
public AdapterTagSpinnerItem(Context context, int resource, List<TagListSimpleSearch> objects, Spinner mySpinner)
{
super(context, resource, objects);
this.listState = objects;
this.mySpinner = mySpinner;
mInflater = LayoutInflater.from(context);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView, ViewGroup parent)
{
String text = "";
final ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.spinner_item, null, false);
holder.mTextView = convertView.findViewById(R.id.tvSpinnerItem);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
/**
* check position , if position is zero we put space on top of list of spinner
*/
if ((position == 0))
text = oneSpace;
/**
* check position , if position is one we put cross mark before text to show that position used to be for clear all selected items on spinner
*/
else if ((position == 1))
text = " " + String.valueOf((char) crossMarkAroundBox) + " " + listState.get(position).getTagText();
/**
* check position , if position is two we put check mark before text to show that position used to be for select all items on spinner
*/
else if ((position == 2))
text = " " + String.valueOf((char) tikMarkAroundBox) + " " + listState.get(position).getTagText();
/**
* check position , if position is bigger than two we have to check that position is selected before or not and put check mark or dash before text
*/
else
{
if (listState.get(position).isSelected())
{
text = " " + String.valueOf((char) tikMark) + " " + listState.get(position).getTagText();
}
else
{
text = " " + String.valueOf(dash) + " " + listState.get(position).getTagText();
}
}
holder.mTextView.setText(text);
holder.mTextView.setTag(position);
holder.mTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/**
* if you want open spinner after click on text for first time we have to open spinner programmatically
*/
mySpinner.performClick();
int getPosition = (Integer) v.getTag();
listState.get(getPosition).setSelected(!listState.get(getPosition).isSelected());
notifyDataSetChanged();
/**
* if clicked position is one
* that means you want clear all select item in list
*/
if (getPosition == 1)
{
clearList();
}
/**
* if clicked position is two
* that means you want select all item in list
*/
else if (getPosition == 2)
{
fillList();
}
}
});
return convertView;
}
/**
* clear all items in list
*/
public void clearList()
{
for (TagListSimpleSearch items : listState)
{
items.setSelected(false);
}
notifyDataSetChanged();
}
/**
* select all items in list
*/
public void fillList()
{
for (TagListSimpleSearch items : listState)
{
items.setSelected(true);
}
notifyDataSetChanged();
}
/**
* view holder
*/
private class ViewHolder
{
private TextView mTextView;
}
}
3- now you have to create object for adapter
public class TagListSimpleSearch {
private String TagId;
private String TagText;
private boolean selected;
public String getTagId() {
return TagId;
}
public void setTagId(String TagId) {
this.TagId = TagId;
}
public String getTagText() {
return TagText;
}
public void setTagText(String tagText) {
TagText = tagText;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
}
4-fill spinner adapter in your activity
public static String oneSpace =" ";
public static int tikMark =0X2714;
public static int crossMark =0X2715;
public static int tikMarkAroundBox =0X2611;
public static int crossMarkAroundBox =0X274E;
public static String dash ="-";
private Spinner mySpinner;
mySpinner= (Spinner) findViewById(R.id.mySpinner);
List<TagListSimpleSearch> tagsNames = new ArrayList<>();
TagListSimpleSearch tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText(oneSpace);
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("select All Items");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("remove All Items");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText("Item 0");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("Item 1");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("Item 2");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("3");
tagSpecific.setTagText("Item 3");
tagsNames.add(tagSpecific);
final AdapterTagSpinnerItem adapterTagSpinnerItem = new AdapterTagSpinnerItem(this, 0, tagsNames,mySpinner);
mySpinner.setAdapter(adapterTagSpinnerItem);
<com.extra.MultiSelectionSpinner
android:id="#+id/input1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp" />
MultiSelectionSpinner spinner=(MultiSelectionSpinner)findViewById(R.id.input1);
List<String> list = new ArrayList<String>();
list.add("List1");
list.add("List2");
spinner.setItems(list);
I have implemented a multiple selection spinner in android using AlertDialog
check the following code
public void classesSelect(){
regclassvalue.setText("");
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setTitle("Select Services");
final int array[] = new int[serarray.length];
check = new boolean[serarray.length];
for (int k = 0; k < serarray.length; k++) {
check[k] = false;
}
final List<String> classlist = Arrays.asList(serarray);
final List<Integer> classidlist = Arrays.asList(classidarray);
// this is the main part here we set the multichoice listener using serarray and check
builder.setMultiChoiceItems(serarray, check, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
check[which] = isChecked;
}
});
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
regclassvalue.setText("");
classids = "";
int io = 0;
for (int ii = 0; ii < check.length; ii++) {
boolean checked = check[ii];
if (checked) {
array[io] = ii;
io++;
}
}
for (int k = 0; k < io; k++) {
if (io == 1) {
classids = classids + classidlist.get(array[k]);
regclassvalue.setText(regclassvalue.getText() + classlist.get(array[k]));
} else if (k == io - 1) {
classids = classids + classidlist.get(array[k]);
regclassvalue.setText(regclassvalue.getText() + classlist.get(array[k]));
} else {
classids = classids + classidlist.get(array[k]) + ",";
regclassvalue.setText(regclassvalue.getText() + classlist.get(array[k]) + " ,");
}
}
//Toast.makeText(RegisterActivity.this,classids,Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
for more info please click here