Search code examples
androidonitemlongclicklistener

my OnItemClickListener and OnItemLongClickListener didn't function at all


This is my MainActivity.java

public class MainActivity extends Activity implements OnClickListener{

    ArrayList<Product> products = new ArrayList<Product>();
    final Context context = this;
    ListAdapter boxAdapter;
     String[] dataArray;
     EditText editText;
     //name that get back through the dialog
     private String getName;
     private String selectedItem;   
     private ArrayAdapter<String> adapter;        // The list adapter





      /** Called when the activity is first created. */
      public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        fillData();
        boxAdapter = new ListAdapter(this, products);

        ListView lvMain = (ListView) findViewById(R.id.lvMain);
        lvMain.setAdapter(boxAdapter);


        Button btn = (Button) findViewById(R.id.AddItem);



        //the add item button function
        btn.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {

            //get the dialog view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.dialog, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.insert);


                // set dialog message
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        // get user input and set it to result
                                        // edit text
                                         getName=userInput.getText().toString();
                                         products.add(new Product(getName,false));

                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();




            }

        });






        // Create the listener for normal item clicks
        OnItemClickListener itemListener = new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long rowid) {

                Toast.makeText(
                        getApplicationContext(),
                        "You have clicked on " + parent.getItemAtPosition(position).toString() + ".",
                        Toast.LENGTH_SHORT).show();
            }
        };




        //the long press to delete function

        OnItemLongClickListener itemLongListener = new OnItemLongClickListener()
        {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    int position, long id) {

                 // Store selected item in global variable
                selectedItem = parent.getItemAtPosition(position).toString();

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("Do you want to remove " + selectedItem + "?");
                builder.setCancelable(false);
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        products.remove(selectedItem);
                        boxAdapter.notifyDataSetChanged();

                        Toast.makeText(
                                getApplicationContext(),
                                selectedItem + " has been removed.",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                // Create and show the dialog
                builder.show();

                // Signal OK to avoid further processing of the long click
                return true;
            }


            };

            lvMain.setOnItemClickListener(itemListener);
            lvMain.setOnItemLongClickListener(itemLongListener);

        }



      void fillData() {

          dataArray = getResources().getStringArray(R.array.ChecklistData);
          for(String productName : dataArray)
          {
            products.add(new Product(productName,false));
          }

      }




    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }




    }

This is ListAdapter.java

public class ListAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<Product> objects;

    ListAdapter(Context context, ArrayList<Product> products) {
        ctx = context;
        objects = products;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.item, parent, false);
        }

        Product p = getProduct(position);

        ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
        /*((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
        ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);*/

        CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
        cbBuy.setOnCheckedChangeListener(myCheckChangList);
        cbBuy.setTag(position);
        cbBuy.setChecked(p.box);
        return view;
    }

    Product getProduct(int position) {
        return ((Product) getItem(position));
    }

    ArrayList<Product> getBox() {
        ArrayList<Product> box = new ArrayList<Product>();
        for (Product p : objects) {
            if (p.box)
                box.add(p);
        }
        return box;
    }

    OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            getProduct((Integer) buttonView.getTag()).box = isChecked;
        }
    };
}

OnItemClickListener and OnItemLongClickListener didn't function at all. Anyone help me out here.. I did diagnose the problem but it still doesn't have function


Solution

    1. implement View.OnItemClickListener and AdapterView.OnItemLongClickListener and their corresponding methods in your class.
    2. initialize your views correctly (findViewById...)
    3. set click listeners to your views (button.setOnClickListener(this) / button.setOnLongClickListener(this)
    4. react to the push events in the implemented methods like:

      @Override
      public void onClick(View v) {
          switch (v.getId()) {
              case R.id.button:
                  this.doSomething();
          }
      }
      

      and

      @Override
      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
          //react to the view or react to the position
          switch (view.getId()) {
      
              case R.id.button:
                  this.doSomething();
          }
          return true;
      }