有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

检测哪个复选框被触摸?Array Java Android Studio

我有一个CheckBox{}设置,但我如何知道哪个被触碰了?更具体地说,我只想得到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。我把它放在箱子里了。行动起来。我现在可以用这个整数来满足我的需要

checkboxPopupCheck = view.getId();

共 (2) 个答案

  1. # 1 楼答案

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

    因此,执行一个简单的view.getId()将返回与设置相同的id

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

    这是ArrayList的整数值

  2. # 2 楼答案

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

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