在listview中的addTextChangedListener中使用自定义列表适配器

时间:2014-03-27 11:40:37

标签: android listview baseadapter

我正在开发创建发票的应用程序。用户必须添加项目列表并设置数量。数据将添加到listview中。我使用自定义列表适配器扩展了基本适配器。第一项如果用户选择数量为15(例如)为item.qty,则显示为15,直到添加下一项。如果添加另一项,则先前设置的数量更改为当前的。我在自定义列表中使用addTextChangedListener Adapter.when我使用addTextChangedListener更改qty所有受影响的行。我正在使用自定义适配器来填充列表视图。列表视图中的每一行都有3个文本视图(自定义布局)和用于输入数量的编辑文本。另一个问题是当滚动ListView时,值会在编辑文本中自动重复/更改。为什么? enter image description here

enter image description here

这是我的主要课程,

public class SalesTransactionFragment extends SherlockFragment {
    Button b1,b2,b3;
    TextView tvcusid,tvcusname,tvtotal;
    ListView lv;
    public static itemlistadapter itadapter;
    static ArrayList<Items>  item ;
    Items it;

    String cus_id,c_name;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Get the view from fragmenttab3.xml
          View view = inflater.inflate(R.layout.salesform, container, false);
          return view;

    }

   @Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    b1=(Button) getActivity().findViewById(R.id.sfbtncus);
    b2=(Button) getActivity().findViewById(R.id.sfbtnadd);
    b3=(Button) getActivity().findViewById(R.id.sfbtfinish);
    itadapter=null;
  it=new Items();
    tvcusid=(TextView) getActivity().findViewById(R.id.sftvcusid);
    tvcusname=(TextView) getActivity().findViewById(R.id.sftvcusname);
    tvtotal=(TextView) getActivity().findViewById(R.id.sftotal);
    lv=(ListView) getActivity().findViewById(R.id.sflvitem);
    lv.setTranscriptMode(lv.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    item = new ArrayList<Items>();

    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(getActivity(), CustomerSelect.class);
            startActivityForResult(i, 1);   
//          Intent i = new Intent(SalesFormActivity.this, CustomerSelect.class);
//          i.putExtra("cussel", "true");
//          startActivityForResult(i, 0);   
        //  Toast.makeText(getActivity(), "CustomerSelect",Toast.LENGTH_LONG).show();
        }
    });
    b2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
//          
            Intent i = new Intent(getActivity(), ItemsView.class);
            startActivityForResult(i, 0);           
//          Toast.makeText(getActivity(), "AddItem",Toast.LENGTH_LONG).show();

        }
    });
    b3.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
        //  Toast.makeText(getActivity(), "Finish",Toast.LENGTH_LONG).show();

             if(itadapter==null)
                {
                        Toast.makeText(getActivity(), "Must select a item", Toast.LENGTH_LONG).show();

                }
         else if(cus_id!=null&&itadapter!=null){
                Intent i=new Intent(getActivity(), Invoice.class);
            i.putExtra("cus_id", cus_id);

                i.putExtra("c_name", c_name);

                startActivity(i);
//                getActivity().finish();

            }
            else if (cus_id==null)
            {
                Toast.makeText(getActivity(), "Must select a customer", Toast.LENGTH_LONG).show();
            }




        }
    });
}
   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(data!=null)
    switch (requestCode) {
//      case 0:
//          cus_id=data.getStringExtra("cus_id");
//          c_name=data.getStringExtra("c_name");
//          tvcusid.setText(cus_id);
//          tvcusname.setText(c_name);
//          
//          break;
    case 0:
        it=new Items();
        it.setitemname(data.getStringExtra("name"));
        it.setprice(data.getDoubleExtra("price",0));
        it.setid(data.getIntExtra("item_id", 0));
        if(itadapter==null){
            item.add(it);
            itadapter=new itemlistadapter(item, getActivity());
            lv.setAdapter(itadapter);
            lv.setSelection(itadapter.getCount()-1);

        }else{

            itadapter.addItems(it);
        }
        if(itadapter!=null){
            tvtotal.setText(""+itadapter.gettotal());
        }
        break;
    case 1:
        cus_id=data.getStringExtra("cusid");
        c_name=data.getStringExtra("cusname");
        tvcusid.setText(cus_id);
        tvcusname.setText(c_name);

        break;
    default:
        break;
    }


   }
   @Override
public void onResume() {
    super.onResume();
}

这是适配器类

public class itemlistadapter extends BaseAdapter implements Filterable {

    ArrayList<Items> item;
    ArrayList<Items> history;
    HashMap<Integer, Double> prices;
    Context con;
    double grantTotal = 0;

    public itemlistadapter(ArrayList<Items> item, Context con) {
        super();
        this.item = item;
        this.con = con;
        history = (ArrayList<Items>) item.clone();
        prices = new HashMap<Integer, Double>();
    }

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

    @Override
    public Object getItem(int position) {
        return item.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater lvinflat = (LayoutInflater) con
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = lvinflat.inflate(R.layout.singlesalelist, parent,
                    false);
        }
        final int pos = position;
        final TextView tvitem = (TextView) convertView
                .findViewById(R.id.sinlvtvname);
        final TextView price = (TextView) convertView
                .findViewById(R.id.sinlvtvprice);

        final EditText qty = (EditText) convertView
                .findViewById(R.id.sinlvetqty);
        if (pos == item.size() - 1) {
            // Log.d("focusposition",
            // ""+pos+"qty.requestFocus()"+qty.requestFocus());
            qty.requestFocus();
        }
        final TextView tvtotal = (TextView) convertView
                .findViewById(R.id.sinlvtvtotal);
        tvitem.setText(item.get(position).getitemname());

        price.setText("" + item.get(position).getprice());

        qty.setText("" + item.get(pos).getqty());
        Log.d("position", "" + pos + "qty" + item.get(position).getqty());

//      if (qty.length() != 0) {
//          int qnty = Integer.parseInt(qty.getText().toString());
//      //  item.get(pos).setqty(qnty);
//      //  Log.d("positionqty.length() != 0:", ""+pos+"qty"+item.get(position).getqty());
//
//          double unitp = Double.parseDouble(price.getText().toString());
//          double total = (qnty * unitp);
//          tvtotal.setText("" + total);
//          prices.put(pos, total);
//      } else {
//
//          tvtotal.setText("" + 0);
//      }
        qty.addTextChangedListener(new TextWatcher() {

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

                Log.d("On text changed", s+",Start:"+start+",count:"+count+",before:"+before);
                if (s.length() != 0) {
                    int qnty = Integer.parseInt(s.toString());
                    item.get(pos).setqty(qnty);
                    Log.d("position in ChangedListener", ""+pos+"qty"+item.get(pos).getqty()+"qnty"+qnty);

                    double unitp = Double.parseDouble(price.getText()
                            .toString());
                    double total = (qnty * unitp);
                    tvtotal.setText("" + total);
                    prices.put(pos, total);
                } else {

                    tvtotal.setText("" + 0);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                Log.d("Before text changed", s+",Start:"+start+",count:"+count+",after:"+after);

            }

            @Override
            public void afterTextChanged(Editable s) {

                Log.d("After text changed", s+"");
            }
        });

        if (tvtotal.getText().equals("total")||tvtotal.getText().equals("Total"))
            tvtotal.setText(price.getText());
        try{
        prices.put(pos, Double.parseDouble(tvtotal.getText().toString()));
        }catch(NumberFormatException e){
            //TODO
        }
        return convertView;
    }

    public void addItems(Items i) {
        item.add(i);
        notifyDataSetChanged();
    }

    public ArrayList<Items> getItems() {
        return item;
    }

    public double gettotal() {
        grantTotal = 0;
        for (int i = 0; i < prices.size(); i++) {
            grantTotal += prices.get(i);
        }
        return grantTotal;
    }

    Filter my_filter = new Filter() {

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            item = (ArrayList<Items>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }

        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            Log.d("insitefilterresults", "msg");
            FilterResults filter_results = new FilterResults();
            ArrayList<Items> arr = new ArrayList<Items>();
            if (constraint != null && history != null) {
                for (Items s : history) {
                    if (s.getitemname().startsWith(constraint.toString()))
                        arr.add(s);
                }
                filter_results.values = arr;
                filter_results.count = arr.size();
            }
            return filter_results;
        }
    };

    @Override
    public Filter getFilter() {
        Log.d("insitegetFilte", "msg");

        // TODO Auto-generated method stub
        return my_filter;
    }

}

LogCat是,

03-27 05:18:57.692: D/Before text changed(409): 1,Start:1,count:0,after:1
03-27 05:18:57.692: D/Before text changed(409): 1,Start:1,count:0,after:1
03-27 05:18:57.702: D/On text changed(409): 15,Start:1,count:1,before:0
03-27 05:18:57.702: D/position in ChangedListener(409): 0qty15qnty15
03-27 05:18:57.722: D/On text changed(409): 15,Start:1,count:1,before:0
03-27 05:18:57.732: D/position in ChangedListener(409): 1qty15qnty15
03-27 05:18:57.742: D/After text changed(409): 15
03-27 05:18:57.742: D/After text changed(409): 15

请帮我解决这个问题。感谢帮助。谢谢。

3 个答案:

答案 0 :(得分:0)

我认为这不是问题我认为你有所有数据的数组列表所以当你在Text Watcher中计算某些内容时那时你必须 将arraylist数据更新为新的计算数据您只需使用put函数进行更新,因为您知道位置值 当你更改足够的值

时,每次更新时都会发生这种情况

答案 1 :(得分:0)

qty.addTextChangedListener

之后的prices.put(pos, total);

添加这段代码。

((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();

答案 2 :(得分:0)

在getView方法中,参数位置给出了新创建的childView的位置,而不是单击的childView的位置

所以,你需要得到正确的位置数字..

点击此链接查看完整详细信息Custom ListView adapter. TextChangedListener calls for wrong EditText

另一个有用的帖子是Android - EditTexts within ListView bound to Custom ArrayAdapter - keeping track of changes