简体   繁体   English

从上到下滚动时如何自动停止对项目的列表视图取消选择?

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

i have one listview and added content using BaseAdapter. 我有一个列表视图,并使用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. 我是新来的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()); // 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 这个示例是使用arraylist假设lstcategory作为您的列表完成的,您也可以为您的hashmap做类似的事情,在这里,我只是展示一个简单的逻辑来解决这个问题,如果您得到了这个逻辑,就可以相应地做到这一点

add boolean flag in your pojo class say 在您的pojo类中添加布尔标志说

Boolean isSelected;

apply getter and setters in it. 在其中应用getter和setter。 initially set all the values for isSelected = false so that no list item is selected 最初将isSelected = false的所有值设置为没有选择任何列表项

now during onItem click set the current Object's isSelected to true like this 现在在onItem单击期间,将当前Object的isSelected设置为true,如下所示

within the onItemClick apply this 在onItemClick中应用此

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. 现在在适配器类的getview中检查列表项是否为Checked。

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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