I have an ImageView source with two colors. I want to touch a color and display a message. I have done the following but something is not going well because maybe I use the method getDrawingCache it has a delay on displaying the correct message..
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView img = (ImageView) findViewById(R.id.imageView);
img.setOnTouchListener(this);
ViewTreeObserver vto = img.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
finalHeight = img.getMeasuredHeight();
finalWidth = img.getMeasuredWidth();
r = (finalHeight*0.2973)*0.8109;
centerx = finalWidth/2;
centery = finalHeight;
Log.e("hilength","Height: " + finalHeight + " Width: " + finalWidth);
img.buildDrawingCache();
bitmap = img.getDrawingCache();
return true;
}
});
And my touch event
@Override
public boolean onTouch(View v, MotionEvent event)
{
switch (v.getId())
{
case R.id.imageView:
Log.d("Tag", "X,Y : " + event.getX() + "," + event.getY());
int x = (int) event.getX();
int y = (int) event.getY();
int pixel = bitmap.getPixel(x,y);
if(pixel == Color.parseColor("#94e3f9"))
{
Toast.makeText(MainActivity.this, "Blue Color", Toast.LENGTH_SHORT).show();
}
if(pixel == Color.parseColor("#f0c828"))
{
Toast.makeText(MainActivity.this, "Yellow Color", Toast.LENGTH_SHORT).show();
}
break;
}
return true;
}
In addition to the above , I am not sure if ViewTreeObserver is needed