我的OnItemClickListener和OnItemLongClickListener根本不起作用

时间:2014-05-18 09:57:39

标签: android onitemlongclicklistener

这是我的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

    }




    }

这是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和OnItemLongClickListener根本不起作用。任何人都帮助我在这里..我确实诊断出了问题,但它仍然没有功能

4 个答案:

答案 0 :(得分:1)

OnItemClickListener itemListener = new OnItemClickListener() {
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {

您只需定义这些变量,但不要将它们分配给ListView。 你应该在某处调用这些行:

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

<强>更新

您也会错过注册上下文菜单列表。

registerForContextMenu(lvMain);

答案 1 :(得分:0)

您需要注册听众。在onCreate()方法的末尾添加以下行。

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

答案 2 :(得分:0)

  1. 在您的班级中实现View.OnItemClickListener和AdapterView.OnItemLongClickListener及其相应的方法。
  2. 正确初始化您的观点(findViewById ...)
  3. 设置单击侦听器到您的视图(button.setOnClickListener(this)/ button.setOnLongClickListener(this)
  4. 对已实现的方法中的推送事件做出反应,如:

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

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

答案 3 :(得分:0)

我遇到了完全相同的问题。在布局中启用onclick或onlongclick时; onitemclickListener不会工作。只需从您的Layout XML资源中删除标签android:clickable和android:longclickable,它们都可以正常工作。