ExpandListview с edittext и слушателем textwatcher. Textwatcher срабатывает несколько раз - PullRequest
0 голосов
/ 03 января 2019

Мы сталкиваемся с проблемой с textwatcherlistener, т. Е. С клавиатурой несколько раз.

Edittext inputtype - это число, но экран, показывающий 2 клавиатуры, т. Е. Число и значение по умолчанию.

мы используем expandlistview (с еще одной динамической информацией в расширенном просмотре), имеет одинредактировать текст.

Edittext с использованием textwatcher слушателя.В childview текстовый код написан.

пытался скрыть клавиатуру, но не работал.

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wavelabs.waterlily.main.R;
import com.wavelabs.waterlily.main.activities.SelectProductActivity;
import com.wavelabs.waterlily.main.model.IGrouponListener;
import com.wavelabs.waterlily.main.model.Product;
import com.wavelabs.waterlily.main.model.ProductCategory;

import java.util.ArrayList;
import java.util.List;

import static android.graphics.Typeface.BOLD;
import static android.view.View.GONE;

public class CategoriesAdapter extends BaseExpandableListAdapter {

    private static final String RETAILERLABEL = "RETAILER";
    private List<ProductCategory> parentData;
    private Context context;
    private IGrouponListener grouponListener;
    private ClickListener clickListener;
    private boolean isResettingKeyboard;

    public CategoriesAdapter(List<ProductCategory> productHeaders, Context context) {
        this.parentData = productHeaders;
        this.context = context;
        this.grouponListener = (IGrouponListener) context;
    }


    @Override
    public int getGroupCount() {
        return parentData.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (parentData.get(groupPosition).isHasSubCategory()) {
            return 1;
        } else {
            int subCategoryCount = parentData.get(groupPosition).getProduct().isEmpty() ? 1 : parentData.get(groupPosition).getProduct().size();
            return subCategoryCount;
        }
//        int subCategoryCount = parentData.get(groupPosition).isHasSubCategory() ? parentData.get(groupPosition).getSubCategories().size() : 0;
//     Log.i("Tag","10");
    }

    @Override
    public Object getGroup(int groupPosition) {
        return parentData.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View inflate = inflater.inflate(R.layout.row_first, null);
        TextView text = inflate.findViewById(R.id.tv_rowParentText);
        CardView card = inflate.findViewById(R.id.card_parent);
        ImageView imageView = inflate.findViewById(R.id.imageView_indicator);
        TextView textViewChild = inflate.findViewById(R.id.tv_rowChildText);
        ImageView imageViewChildIndicator = inflate.findViewById(R.id.imageViewChild_indicator);

        ProductCategory productCategory = parentData.get(groupPosition);
        String parentId = productCategory.getParentCatId();

        if (parentId.equals("null")) {
            text.setVisibility(View.VISIBLE);
            card.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.VISIBLE);
            textViewChild.setVisibility(GONE);
            imageViewChildIndicator.setVisibility(GONE);
            text.setTextAppearance(R.style.TextAppearance_AppCompat_Large);
            text.setTextColor(text.getContext().getColor(R.color.textcolor));
            text.setTypeface(null, BOLD);
            String name = productCategory.getName();
            name = name.substring(0,1)+name.substring(1,name.length()).toLowerCase();
            text.setText(name.trim());
            if (isExpanded) {
                imageView.setImageResource(R.mipmap.arrowup_black);
            } else {
                imageView.setImageResource(R.mipmap.arrowdown_black);
            }
        } else {
            text.setVisibility(View.GONE);
            card.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
            textViewChild.setVisibility(View.VISIBLE);
            imageViewChildIndicator.setVisibility(View.VISIBLE);
            textViewChild.setTextAppearance(R.style.TextAppearance_AppCompat_Medium);
            textViewChild.setAllCaps(false);
            textViewChild.setTypeface(null, BOLD);
            textViewChild.setTextColor(text.getContext().getColor(R.color.textcolor));
            String name = productCategory.getName();
            name = name.substring(0,1)+name.substring(1,name.length()).toLowerCase();
            textViewChild.setText(name.trim());
            if (isExpanded) {
                imageViewChildIndicator.setImageResource(R.mipmap.arrowup_black);
            } else {
                imageViewChildIndicator.setImageResource(R.mipmap.arrowdown_black);
            }
        }
        return inflate;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, final View convertView, ViewGroup parent) {
        final ProductCategory productCategory = parentData.get(groupPosition);
        View inflate;
        if (parentData.get(groupPosition).isHasSubCategory()) {
            final ChildLevelExpandableListView childLevelExpandableListView = new ChildLevelExpandableListView(context);
            final List<ProductCategory> subCategories = parentData.get(groupPosition).getSubCategories();
            final CategoriesAdapter categoriesAdapter = new CategoriesAdapter(subCategories, context);
            categoriesAdapter.setOnItemClickListener(clickListener);
            childLevelExpandableListView.setAdapter(categoriesAdapter);
            childLevelExpandableListView.setGroupIndicator(null);
            childLevelExpandableListView.setDividerHeight(2);
            childLevelExpandableListView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            childLevelExpandableListView.setScrollBarSize(0);
            childLevelExpandableListView.setPadding(25,0,25,0);

            childLevelExpandableListView.setItemsCanFocus(true);
            childLevelExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                @Override
                public void onGroupExpand(int groupPosition) {
                    if(childLevelExpandableListView.isGroupExpanded(groupPosition)){
                        Log.i("TAG","isExpanded");
                    }
                    if (grouponListener != null) {
                        grouponListener.onGroupExpandedListener(subCategories.get(groupPosition), categoriesAdapter,childLevelExpandableListView,groupPosition);
                    }
                }
            });


            childLevelExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                    return false;
                }
            });
            return childLevelExpandableListView;
        } else {
            if (!productCategory.getProduct().isEmpty()) {
                LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                inflate = layoutInflater.inflate(R.layout.item_product_list, null);
                TextView tvName = inflate.findViewById(R.id.tv_listProductItem_name);
                TextView tvCost = inflate.findViewById(R.id.tv_listProductItem_cost);
                final Button btnAdd = inflate.findViewById(R.id.btn_productList_add);
                final LinearLayout llAdditem = inflate.findViewById(R.id.ll_product_additem);
                final TextView tvProductQty = inflate.findViewById(R.id.tv_productQty);
                final EditText amount = inflate.findViewById(R.id.amount);
                final Product product = productCategory.getProduct().get(childPosition);
                String productName = product.getProductName();
                tvName.setText(productName.trim());
                amount.setTag(R.id.amount, childPosition);
                if (context instanceof SelectProductActivity) {
                    SelectProductActivity selectProductActivity = (SelectProductActivity) context;
                    Product productAvailable = selectProductActivity.isProductAvailable(product);

amount.addTextChangedListener(new TextWatcher() {
                       boolean editing = false;

                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            String enteredAmount = s.toString();
                            Object tag = amount.getTag(R.id.amount);
                            Log.d("position",""+tag);

                            if(!editing) {
                                editing = true;
                                if (enteredAmount.length() > 0) {
                                    try {
                                        final int amountselected = Integer.parseInt(enteredAmount);
                                        product.setCategoryName(productCategory.getName());
                                        product.setSubcategoryName(productCategory.getName());
                                        Log.i("cat name ",""+product.getCategoryName());
                                        product.setSelectedQty(amountselected);
                                        if (product.getCustomerType().equals(RETAILERLABEL)) {
                                            Log.d("Prodyct Adapter ",product.getProductName());
                                            clickListener.onItemClick(childPosition, amount, "plus", product.getRrp(), amountselected, product);
                                        } else {
                                            Log.d("Prodyct Adapter ",product.getProductName());
                                            clickListener.onItemClick(childPosition, amount, "plus", product.getDrp(), amountselected, product);

                                        }

                                    }catch(Exception ex){
                                        ex.printStackTrace();
                                    }

                                } else {
                                    InputMethodManager imm = (InputMethodManager) convertView.getContext()
                                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.hideSoftInputFromWindow(convertView.getWindowToken(), 0);
                                    amount.getText().clear();
                                    amount.append("");

                                }

                                editing = false;

                            }

                        }

                    });
                    if (productAvailable != null) {
                        product.setSelectedQty(productAvailable.getSelectedQty());
                        tvProductQty.setText("" + productAvailable.getSelectedQty());
                        amount.setText("" + productAvailable.getSelectedQty());
                        Log.i("qty", "" + productAvailable.getSelectedQty());
                    } else {
                        tvProductQty.setText("0");
                        product.setSelectedQty(0);
                        amount.setText("0");
                        if (product.getSelectedQty() == 0) {
                            Log.i("productname in Adapter:",""+product.getProductName());
                            Log.i("productQty in Adapter:",""+product.getSelectedQty());
                            llAdditem.setVisibility(View.GONE);
                            btnAdd.setVisibility(View.VISIBLE);
                        }
                    }
                }

                if (product.getCustomerType().equals(RETAILERLABEL)) {
                    String s = parent.getResources().getString(R.string.rupeeSymbol) +" "+product.getRrp();
                    tvCost.setText(s.trim());
                } else {
                    String s = parent.getResources().getString(R.string.rupeeSymbol) +" "+product.getDrp();
                    tvCost.setText(s.trim());
                }

                tvProductQty.setText("" + product.getSelectedQty());

                if (product.getSelectedQty() >= 1) {
                    btnAdd.setVisibility(View.INVISIBLE);
                    llAdditem.setVisibility(View.VISIBLE);
                } else {
                    Log.i("TAG", "Called Child Position" + childPosition + " And Quantity is " + product.getSelectedQty());
                    llAdditem.setVisibility(View.INVISIBLE);
                    btnAdd.setVisibility(View.VISIBLE);

                }

                btnAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        btnAdd.setVisibility(View.GONE);
                        llAdditem.setVisibility(View.VISIBLE);
                        product.setSelectedQty(1);
                        product.setSubcategoryName(productCategory.getName());
                        Log.i("Add Button Clicked", tvProductQty.getText().toString());

                    }
                });


                final ImageView imgDecreaseQty = inflate.findViewById(R.id.img_decreaseQty);
                ImageView imgIncreaseQty = inflate.findViewById(R.id.img_increaseQty);


                imgIncreaseQty.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        llAdditem.setVisibility(View.VISIBLE);
                        btnAdd.setVisibility(View.GONE);
                        String s = tvProductQty.getText().toString();
                        int qty = Integer.parseInt(s) + 1;
                        product.setSelectedQty(qty);
                        tvProductQty.setText("" + qty);

                    }
                });

                imgDecreaseQty.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String s = tvProductQty.getText().toString();
                        int qty = Integer.parseInt(s);
                        if(product.getSelectedQty()>=1) {
                            if (qty > 1) {
                                qty = qty - 1;
                                tvProductQty.setText("" + qty);
                                product.setSelectedQty(qty);
                            } else if (qty == 1) {
                                llAdditem.setVisibility(View.GONE);
                                btnAdd.setVisibility(View.VISIBLE);
                                qty = 0;
                                product.setSelectedQty(qty);
                                tvProductQty.setText("" + qty);
                            }
                     }
                    }

                });
            } else {
                LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                inflate = layoutInflater.inflate(R.layout.empty_layout, null);
            }

        }

        return inflate;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }



    public void setOnItemClickListener(ClickListener clickListener) {
        this.clickListener = clickListener;
    }

    public interface ClickListener {
        void onItemClick(int position, View v, String type, double price, int quantity, Product product);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...