簡體   English   中英

檢測哪個復選框被觸摸? 數組 Java Android Studio

[英]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.getId()會返回你設置的相同 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 } } });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM