检测触摸了哪个复选框?数组 Java Android 工作室

Detect which checkbox is touched? Array Java Android Studio

我有一个 CheckBox ArrayList 设置,但我怎么知道哪个被触摸了?更具体地说,我只想在已触摸复选框的 ArrayList 中获取 "i" 的整数值。有任何想法吗?

@Override
    public void sendData(String userText, String userNotes) {

        //we can create the saves here as well....

        LinearLayout ll = (LinearLayout)findViewById(R.id.myLayout);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        CheckBox tv = new CheckBox(getApplicationContext());
        tv.setTextSize(20);
        tv.setText(userText + "  \n" + date);
        tv.setLayoutParams(lp);
        checkBoxArrayList.add(tv);

        //Handles if checkbox is pressed down, and set id for each check box
        for(int i = 0; i < checkBoxArrayList.size(); i ++){

            checkBoxArrayList.get(i).setId(i);

            checkBoxArrayList.get(i).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {

                    switch(motionEvent.getAction()) {

                        case MotionEvent.ACTION_DOWN:
                            //here we will simply open the files unless held down

                            //when held down
                            view.postDelayed(runnable, 1250);
                            break;

                    }
                    return false;
                }
            });
            }

            //add checkbox passed in to the layout
            ll.addView(tv);
        }

多亏了@rex,我才有了一个全局私有整数 checkboxPopupCheck。我将它添加到案例 MotionEvent.ACTION_DOWN 中。我现在可以使用这个整数来满足我的需要。

checkboxPopupCheck = view.getId();

你的onTouch方法有两个参数,第一个是被触摸的view。

所以做一个简单的 view.getId() 会 return 你与你设置的相同的 ID

checkBoxArrayList.get(i).setId(i);

这就是 ArrayList 的整数值

在你的适配器中尝试这段代码,点击复选框,你必须创建一个新的数组列表,并将持有者的位置或值添加到数组列表中,这样你就可以知道正在处理的项目是什么已检查。

holderItem.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    // add in to a arraylist 
                }else{
                    // remove it from arraylist
                }

            }
        });