pewpew pewpew - 3 years ago 253
Java Question

Detect which checkbox is touched? Array Java Android Studio

I have a

CheckBox
ArrayList
set up, but how do I know which one is touched? More specifically I simply would like to get the integer value of "i" in the
ArrayList
of which checkbox has been touched. Any ideas?

@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 rex
Answer Source

Your onTouch Method has two parameters, the first is the view that was touched.

So doing a simple view.getId() would return you the same id that you set with

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

and that's the integer value of the ArrayList

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download