简体   繁体   中英

how to stop listview deselection on items automatically when scrolling top to bottom?

i have one listview and added content using BaseAdapter. it's working fine but when am going to scroll down items form top to bottom it automatically change the stage of selected items to default state in listview. how to solve this problem. please help. i new to android.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sub_menu_list);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    customDialog = new CustomDialog(TakeoutListActivity.this);
    Intent intent = getIntent();
    Obj = intent.getStringExtra("CateValue");
    Log.e("Obj", "" + Obj);

    addtocardArr = new ArrayList<HashMap<String, String>>();
    listView = (ListView) findViewById(R.id.subcategory_list);
    notificationCount = 0;
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            customDialog.setContentView(R.layout.cus_dialog);
            customDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {

            if (Obj != null) {

                try {
                    JSONObject jsonObject = new JSONObject(Obj);
                    JSONArray jsonArray = jsonObject.getJSONArray("Details");

                    SubCateArrayList = new ArrayList<HashMap<String, String>>();

                    /*for (int i = 0; i < jsonArray.length(); i++) {
                        SubCateHashMapList = new HashMap<String, String>();
                        JSONObject DetailsObj = jsonArray.getJSONObject(i);

                        SubCateHashMapList.put("ItemName", DetailsObj.optString("ItemName"));
                        JSONArray AllItemArray = DetailsObj.getJSONArray("Allitems");
                        //Log.e("AllItemArray", "" + AllItemArray);

                        SubCateArrayList.add(SubCateHashMapList);

                        for (int j = 0; j < AllItemArray.length(); j++) {
                            SubInner = new HashMap<String, String>();
                            JSONObject AllItemObj = AllItemArray.getJSONObject(j);
                            SubInner.put("foodid", AllItemObj.getString("foodid"));
                            SubInner.put("name", AllItemObj.getString("name"));
                            SubInner.put("Description", AllItemObj.getString("Description"));
                            SubInner.put("image", AllItemObj.getString("image"));
                            SubInner.put("price", AllItemObj.getString("price"));
                            SubInner.put("favorite", AllItemObj.getString("favorite"));

                            SubCateArrayList.add(SubInner);
                            Log.e("SubCateArrayList", "" + SubCateArrayList);
                        }
                    }
                    Log.e("SubCateArrayList", "" + SubCateArrayList);*/


                    SubCateArrayList = new ArrayList<HashMap<String, String>>();
                    // SubCateArrayList.clear();
                    // SubCateInnerArrayList = new ArrayList<HashMap<String, String>>();

                    for (int i = 0; i < jsonArray.length(); i++) {
                        SubCateHashMapList = new HashMap<String, String>();
                        JSONObject DetailsObj = jsonArray.getJSONObject(i);

                        SubCateHashMapList.put("ItemName", DetailsObj.optString("ItemName"));
                        Log.e("SubCateHashMapList>>>>>>>>>", "" + SubCateHashMapList);
                        JSONArray AllItemArray = DetailsObj.getJSONArray("Allitems");
                        //Log.e("AllItemArray", "" + AllItemArray);

                        //SubCateArrayList.add(SubCateHashMapList);


                        for (int j=0; j<AllItemArray.length();j++)
                        {
                            SubInner = new HashMap<String, String>();

                            JSONObject AllItemObj = AllItemArray.getJSONObject(j);
                            SubInner.put("foodid", AllItemObj.getString("foodid"));
                            SubInner.put("name", AllItemObj.getString("name"));
                            SubInner.put("Description", AllItemObj.getString("Description"));
                            SubInner.put("image", AllItemObj.getString("image"));
                            SubInner.put("price", AllItemObj.getString("price"));
                            SubInner.put("favorite", AllItemObj.getString("favorite"));


                            SubCateArrayList.add(SubInner);
                            Log.d("SubCateInnerArrayList2349587", "" + SubCateArrayList);
                        }
                        //SubInner.putAll(SubCateHashMapList);
                    }

                    Log.e("SubCateArrayList", "" + SubCateArrayList);


                } catch (JSONException e) {
                    e.printStackTrace();
                }


            } else {

                ErrorMsg = "JSONError";
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            customDialog.dismiss();
            subCateListAdapter = new SubCateListAdapter(TakeoutListActivity.this, SubCateArrayList);
            subCateListAdapter.notifyDataSetInvalidated();
            listView.setFadingEdgeLength(0);
            listView.setAdapter(subCateListAdapter);


        }
    }.execute();


}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.cart_menu,menu);

    MenuItem item = menu.findItem(R.id.cart_add);
    drawable = (LayerDrawable)item.getIcon();

    Log.d("notificationCount", "" + notificationCount);
    BadgeHelper.setBadgeCount(this, drawable, notificationCount);


    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.cart_homeID)
    {
        Intent homeIntent = new Intent(TakeoutListActivity.this,HomeRestaurant.class);
        startActivity(homeIntent);
        TakeoutListActivity.this.finish();
    }
    if (id==R.id.cart_add)
    {
        if (notificationCount==0)
        {

            AlertDialog.Builder builder = new AlertDialog.Builder(TakeoutListActivity.this);
            builder.setMessage("Please add to cart");
            builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
        else
        {
            Intent nextact = new Intent(TakeoutListActivity.this, AddCartActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("Selected", addtocardArr);
            nextact.putExtras(bundle);

            // nextact.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(nextact);

// Log.d("addtocardmap final", "********" + addtocardmap.toString());

        }
        return  true;
    }

    return super.onOptionsItemSelected(item);
}

private class SubCateListAdapter extends BaseAdapter {

    LayoutInflater layoutInflater;
    Context context;
    HashMap<String, String> display = new HashMap<String, String>();
    ArrayList<HashMap<String, String>> data;


    int count = 0;
    String strcount="";
    String[] clickedpositions;
    int locid;

    HashMap<String,String> toaddData;

    public SubCateListAdapter(Context subMenuListActivity, ArrayList<HashMap<String, String>> subCateArrayList) {

        this.context = subMenuListActivity;
        this.data = subCateArrayList;

    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final TextView menuTitle, subMenuTitle, Price, des, countText, addCart, remove;
        ImageView itemImage, FavImage;
        ImageButton add, minus;

        toaddData = new HashMap<String,String>();


        display = data.get(position);
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view =layoutInflater.inflate(R.layout.takeout_listitem, parent, false);

        //menuTitle = (TextView)view.findViewById(R.id.menu_title);
        subMenuTitle = (TextView) view.findViewById(R.id.sub_title);
        Price = (TextView) view.findViewById(R.id.price);
        countText = (TextView) view.findViewById(R.id.count_text);
        des = (TextView) view.findViewById(R.id.menu_des);
        itemImage = (ImageView) view.findViewById(R.id.menu_Image);
        FavImage = (ImageView) view.findViewById(R.id.fav);
        addCart = (TextView)view.findViewById(R.id.addToCart);

        add = (ImageButton)view.findViewById(R.id.add);
        minus = (ImageButton)view.findViewById(R.id.minus);


        //menuTitle.setText(display.get("ItemName"));
        subMenuTitle.setText(display.get("name"));
        des.setText(display.get("Description"));
        Price.setText(display.get("price"));
        Glide.with(getApplicationContext()).load(display.get("image")).error(R.drawable.list_bg).crossFade(500).into(itemImage);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                textCount = Integer.parseInt(countText.getText().toString());
                textCount++;
                strcount = String.valueOf(textCount);
                countText.setText(strcount);
            }
        });

        minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int textCount = Integer.parseInt(countText.getText().toString());
                textCount--;

                if(textCount<=0) {
                    strcount = String.valueOf(textCount);
                    countText.setText("0");
                }
                else
                {
                    strcount = String.valueOf(textCount);
                    countText.setText(strcount);
                }

            }
        });

        addCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                addtocardmap = new HashMap<String, String>();
                recid = data.get(position).get("foodid");
                pdttitle = data.get(position).get("name");
                foodprice = data.get(position).get("price");
                notifycount = countText.getText().toString();
                poscount +=position;
                strposcount += String.valueOf(position) + ",";
                Log.e("strposcount", "" + strposcount);

                toaddData.put("foodid", recid);
                toaddData.put("name", pdttitle);
                toaddData.put("notifycount", notifycount);

                if(addtocardArr.contains(addtocardmap))
                {
                    String quan = addtocardArr.get(position).get("qunatity");
                    int intquan = Integer.parseInt(quan)+Integer.parseInt(strcount);
                    strcount = String.valueOf(intquan);

                    // addtocardArr.remove(position - 1);
                    addtocardmap.put("foodid", recid);
                    addtocardmap.put("name", pdttitle);
                    addtocardmap.put("price", foodprice);
                    addtocardmap.put("qunatity", notifycount);
                    addtocardArr.set(position,addtocardmap);


                    Log.d("recid", "******" + recid);
                    Log.d("pdttitle", "******" + pdttitle);
                    Log.d("Quantity", "******" + notifycount);
                    Log.d("foodprice", "******" + foodprice);
                    Log.d("item position", "******" + position);
                    Log.d("addtocardmap", "********" + addtocardmap);
                    //addtocardArr.remove(position);
                    Log.d("After remove duplicates", "********" + addtocardArr);
                }
                else
                {
                    //in object
                    addtocardmap.put("foodid", recid);
                    addtocardmap.put("name", pdttitle);
                    addtocardmap.put("price", foodprice);
                    addtocardmap.put("qunatity", notifycount);
                    //in array
                    Log.d("recid", "******" + recid);
                    Log.d("pdttitle", "******" + pdttitle);
                    Log.d("Quantity", "******" + notifycount);
                    Log.d("foodprice", "******" + foodprice);
                    Log.d("item position", "******" + position);
                    Log.d("addtocardmap", "********" + addtocardmap);

                }
                //tosendData.add(toaddData);
                addtocardArr.add(addtocardmap);
                Log.d("to add non-duplicate element", "" + addtocardArr);

                // addtocardArr.add(new SelectedItems());

                notificationCount++;
                updateNotificationCount(String.valueOf(notificationCount));

            }
        });


        return view;
    }
}

See my Adapter and change your adapter like that

 @Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    ViewHolder holder = null;
    if (view == null) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_list_item, null);
        holder = new ViewHolder();
        holder.title = (TextView) view.findViewById(R.id.tvFoodItemTitle);
        holder.desc = (TextView) view.findViewById(R.id.tvFoodItemDesc);
        holder.image = (ImageView) view.findViewById(R.id.ivFoodItem);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    holder.title.setText(getItem(position).getName());
    holder.desc.setText(getItem(position).getDescription());
    String imagePath = "assets://" + getItem(position).getImagePath();
    ImageLoader.getInstance().displayImage(imagePath, holder.image);

    return view;
}

class ViewHolder {
    TextView title;
    TextView desc;
    ImageView image;
}

This example is done using the arraylist assuming lstcategory as your list and you can do similar for your hashmap too here I am just showing a simple logic to solve this you can do it accordingly if you get this logic

add boolean flag in your pojo class say

Boolean isSelected;

apply getter and setters in it. initially set all the values for isSelected = false so that no list item is selected

now during onItem click set the current Object's isSelected to true like this

within the onItemClick apply this

OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {

for(int i =0;i  < lstcategory.size();i++}{
lstcategory.get(i).setIsSelected(false);
}

lstcategory.get(position).setIsSelected(true); 
            mAdapter.notifyDataSetChanged();

    }
};

now in getview of your adapter class check if the lists item isChecked or not.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final View view = View.inflate(context, R.layout.item_list, null);

    if (lstcategory.get(position).getIsSelected()) {
        // set selected your color
    }else{
       //set default color
    }


    return view;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM