this is my code
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout rLinear=new LinearLayout(this);
rLinear.setId(200);
for (int c=0;c<5;c++)
{
ImageView imEdit = new ImageView(this);
imEdit.setId(300+c);
imEdit.setImageResource(R.drawable.a);
imEdit.setLayoutParams(new LayoutParams(36, 36));
rLinear.addView(imEdit);
}
}
}
Okay, I have this code, I'm adding 5 ImageView to an linear layout at runtime, so far so good, but what i would like to do is, when the user slide his finger over one of them, i would like to change the image, so my question would be, how can i know what's the current imageview under the user finger.??
Thanks.
This is what I've used to find a first non-ViewGroup view under finger. It is recursive and uses getGlobalVisibleRect
private View findViewAtPosition(View parent, int x, int y) {
if (parent instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup)parent;
for (int i=0; i<viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
View viewAtPosition = findViewAtPosition(child, x, y);
if (viewAtPosition != null) {
return viewAtPosition;
}
}
return null;
} else {
Rect rect = new Rect();
parent.getGlobalVisibleRect(rect);
if (rect.contains(x, y)) {
return parent;
} else {
return null;
}
}
}
Usage example:
public boolean onTouchEvent(MotionEvent ev) {
Log.i(TAG, "View under finger: " + findViewAtPosition(getRootView(), (int)ev.getRawX(), (int)ev.getRawY()));
}
Apply
rLinear.setOnTouchListener(new OnTouchListener() {@Override
public boolean onTouch(View v, MotionEvent event) {
String eventName = "";
LinearLayout layout = (LinearLayout)v;
for(int i =0; i< layout.getChildCount(); i++)
{
View view = layout.getChildAt(i);
Rect outRect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
if(outRect.contains((int)event.getX(), (int)event.getY()))
{
Log.d("", view.getId());
}
}
}});
ps: this code button is a mess
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With