Play two sound together on two button touch using soundpool - android

I am trying to play two sound together when two button is touch together at the same time. I have button1 and button2, while button1 is touch, button2 wont play the sound. But when I put my finger off button1 then touching button2 plays the sound.
I have tried googling around but couldn't find an answer.
What I wanted to do is clear. Play two sound together when two buttons are touch together.
Below is my code so far.
public class MultitouchtestActivity extends MultiTouchActivity {
/** Called when the activity is first created. */
private Button btn1;
private Button btn2;
SoundPool soundPool;
AudioManager audioManager;
int soundId;
int kID, sID;
#Override
public void onCreate(Bundle savedInstanceState)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
super.onCreate(savedInstanceState);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
//the maximum number of simultaneous streams for this SoundPool object
int maxStreams = 4;
//the audio stream type as described in AudioManager
int streamType = AudioManager.STREAM_MUSIC;
//the sample-rate converter quality. Currently has no effect. Use 0 for the default.
int srcQuality = 0;
soundPool = new SoundPool(maxStreams, streamType, srcQuality);
soundPool.setOnLoadCompleteListener(soundPoolOnLoadCompleteListener);
soundId = soundPool.load(this, R.raw.c, 1);
kID = soundPool.load(this, R.raw.k, 1);
sID = soundPool.load(this, R.raw.s, 1);
btn1.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
float vol = audioManager.getStreamVolume(
AudioManager.STREAM_MUSIC);
float maxVol = audioManager.getStreamMaxVolume(
AudioManager.STREAM_MUSIC);
float leftVolume = vol/maxVol;
float rightVolume = vol/maxVol;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(kID,
leftVolume,
rightVolume,
priority,
no_loop,
normal_playback_rate);
return true;
}
return false;
}
});
btn2.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
float vol = audioManager.getStreamVolume(
AudioManager.STREAM_MUSIC);
float maxVol = audioManager.getStreamMaxVolume(
AudioManager.STREAM_MUSIC);
float leftVolume = vol/maxVol;
float rightVolume = vol/maxVol;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(sID,
leftVolume,
rightVolume,
priority,
no_loop,
normal_playback_rate);
return true;
}
return false;
}
});
}
SoundPool.OnLoadCompleteListener soundPoolOnLoadCompleteListener = new SoundPool.OnLoadCompleteListener()
{
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status)
{
if(status==0)
{
btn1.setEnabled(true);
btn2.setEnabled(true);
}
else
{
Toast.makeText(MultitouchtestActivity.this,"SoundPool.load() fail", Toast.LENGTH_LONG).show();
}
}
};
}
public class MultiTouchActivity extends Activity implements OnTouchListener {
private View parent;
public void onCreate(Bundle instance)
{
super.onCreate(instance);
parent = findViewById(android.R.id.content).getRootView();
parent.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
for (int ptrIndex = 0; ptrIndex < event.getPointerCount(); ptrIndex++) {
// index of the pointer which starts this Event
int actionPointerIndex = event.getActionIndex();
// resolve the action as a basic type (up, down or move)
int actionResolved = event.getAction() & MotionEvent.ACTION_MASK;
if (actionResolved < 7 && actionResolved > 4) {
actionResolved = actionResolved - 5;
}
if (actionResolved == MotionEvent.ACTION_MOVE) {
dealEvent(ptrIndex, event, v, actionResolved);
Log.v("tag", "move" + ptrIndex);
} else {
dealEvent(actionPointerIndex, event, v, actionResolved);
}
}
return false;
}
private void dealEvent(int actionPointerIndex, MotionEvent event,
View eventView, int actionresolved) {
int rawX, rawY;
int location[] = { 0, 0 };
eventView.getLocationOnScreen(location);
// Log.v("tag", location + "");
rawX = (int) event.getX(actionPointerIndex) + location[0];
rawY = (int) event.getY(actionPointerIndex) + location[1];
ArrayList<View> views = getTouchedViews(rawX, rawY, actionresolved);
// dumpEvent(event);
for (View view : views) {
int x, y;
view.getLocationOnScreen(location);
x = rawX - location[0];
y = rawY - location[1];
// Log.v("tag", "touched" + view.toString());
/*
* view.onTouchEvent(MotionEvent.obtain(event.getDownTime(),
* event.getEventTime(), event.getActionMasked(), x, y,
* event.getMetaState()));
*/
// MotionEvent me = MotionEvent.obtain(event);
MotionEvent me = MotionEvent.obtain(event.getDownTime(),
event.getEventTime(), actionresolved, x, y,
event.getPressure(actionPointerIndex),
event.getPressure(actionPointerIndex),
event.getMetaState(), event.getXPrecision(),
event.getYPrecision(), event.getDeviceId(),
event.getEdgeFlags());
me.setLocation(x, y);
// Log.v("tag", "oldeventid: " + event.getAction() + " #" +
// actionPointerIndex+ " id" + ptrId+ " resolved "+ actionResolved);
// Log.v("tag", "neweventid: " + me.getAction() + " #" +
// actionPointerIndex+ " id" + ptrId+ " resolved "+ actionResolved);
if (!me.equals(event)) {
/*
* Log.v("tag", "actionindex: " + actionPointerIndex +
* " resolved: " + actionPointerIndex + " to " + view.toString()
* + " y:" + view.getTop() + "-" + (view.getTop() +
* view.getHeight()));
*/
// me.setAction(actionresolved);
view.onTouchEvent(me);
}
if (actionresolved == MotionEvent.ACTION_MOVE) {
Log.v("tag",
"#" + actionPointerIndex + "Rawx:" + rawX + " rawy:"
+ rawY + "x:" + x + " y:" + y + " "
+ view.toString());
}
}
}
private ArrayList<View> getTouchedViews(int x, int y, int action) {
int moveGap = 0;
if (action == MotionEvent.ACTION_MOVE) {
moveGap = 0;
}
ArrayList<View> touchedViews = new ArrayList<View>();
ArrayList<View> possibleViews = new ArrayList<View>();
if (parent instanceof ViewGroup) {
possibleViews.add(parent);
for (int i = 0; i < possibleViews.size(); i++) {
View view = possibleViews.get(i);
int location[] = { 0, 0 };
view.getLocationOnScreen(location);
if (((view.getHeight() + location[1] + moveGap >= y)
& (view.getWidth() + location[0] + moveGap >= x)
& (view.getLeft() - moveGap <= x) & (view.getTop()
- moveGap <= y))
|| view instanceof FrameLayout) {
touchedViews.add(view);
possibleViews.addAll(getChildViews(view));
}
}
}
return touchedViews;
}
private ArrayList<View> getChildViews(View view) {
ArrayList<View> views = new ArrayList<View>();
if (view instanceof ViewGroup) {
ViewGroup v = ((ViewGroup) view);
if (v.getChildCount() > 0) {
for (int i = 0; i < v.getChildCount(); i++) {
views.add(v.getChildAt(i));
}
}
}
return views;
}
}

Related

I can not use MotionEvent with Rajawali

Rajawali Version or Branch
rajawali:1.0.186
Device and Android Version
ADV Nexus 5X API 19 Android 4.4
Summary
I'm trying to make the camera moves when a MotionEvent (touch) occurs. I tried the code from https://github.com/Rajawali/Rajawali/issues/428 but it did not work for me.
My code
public class Renderer extends RajawaliRenderer {
public Context context;
private DirectionalLight directionalLight;
public Renderer(Context context) {
super(context);
this.context = context;
setFrameRate(60);
}
private Object3D object, star;
public void initScene(){
getCurrentScene().setBackgroundColor(Color.rgb(5,104,255));
directionalLight = new DirectionalLight(1f, .2f, -1.0f);
directionalLight.setColor(1.0f, 1.0f, 1.0f);
directionalLight.setPower(2);
getCurrentScene().addLight(directionalLight);
//LoaderOBJ objParser = new LoaderOBJ(this,"Load/1c_obj");
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),mTextureManager, R.raw.primo_obj);
LoaderOBJ starParser = new LoaderOBJ(mContext.getResources(),mTextureManager,R.raw.star_obj);
try {
objParser.parse();
starParser.parse();
object = objParser.getParsedObject();
star = starParser.getParsedObject();
getCurrentScene().addChild(star);
getCurrentScene().addChild(object);
} catch (ParsingException e) {
e.printStackTrace();
}
getCurrentCamera().setLookAt(object.getWorldPosition());
Log.d("->",getCurrentCamera().getX()+","+getCurrentCamera().getY()+","+getCurrentCamera().getZ());
getCurrentCamera().setZ(40);
}
#Override
public void onRender(final long elapsedTime, final double deltaTime) {
super.onRender(elapsedTime, deltaTime);
Camera cam = getCurrentCamera();
Vector3 s = cam.getPosition();
if (touchTurn != 0) {
if (flagMulti) {
Double r = Math.sqrt(s.x * s.x + s.z * s.z);
angle += touchTurn;
angle %= 360;
cam.setPosition((float) (r * Math.cos(angle)), s.y, (float) (r * Math.sin(angle)));
cam.setLookAt(object.getLookAt());
}
else{
s.x+=touchTurn*5;
cam.setPosition(s);
}
touchTurn = 0;
}
if (touchTurnUp != 0) {
if (!flagMulti) {
s.z += touchTurnUp * 5;
cam.setPosition(s);
}
touchTurnUp = 0;
}
}
#Override
public void onTouchEvent(MotionEvent me){
Log.d("touch ","Log touch");
int pointerCount = me.getPointerCount();
if(pointerCount == 2)
flagMulti = true;
if (me.getAction() == MotionEvent.ACTION_DOWN) {
xpos = me.getX();
ypos = me.getY();
}
if (me.getAction() == MotionEvent.ACTION_UP) {
xpos = -1;
ypos = -1;
touchTurn = 0;
touchTurnUp = 0;
}
if (me.getAction() == MotionEvent.ACTION_MOVE) {
float xd = me.getX() - xpos;
float yd = me.getY() - ypos;
xpos = me.getX();
ypos = me.getY();
touchTurn = xd / -100f;
touchTurnUp = yd / -100f;
Log.d("touchTurn ", touchTurn+" - "+touchTurnUp);
}
try {
Thread.sleep(15);
} catch (Exception e) {
}
}
public void onOffsetsChanged(float x, float y, float z, float w, int i, int j){
}}
Would you consider arcballCamera and target to your 3D object. You can then rotate the 3D object and zoom in/out with arcballCamera.

Tap image to get rgb value at a specific point

I am trying to get rgb value at a point on image where user taps. I am using following code to achieve that.
imageView.setOnTouchListener(new ImageView.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int x=0;
int y=0;
ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
if(pixel == Color.RED){
}
Log.v("RGB",pixel+ " :R: "+redValue+ " G: "+blueValue+ " B:"+greenValue);
return true; }
});
But it returns same value of RGB for every point on the image that is "-10197916 :R: 100 G: 100 B:100".
I have even used int x=(int)event.getIntX();
int y=(int)event.getIntY();
But result is always same. What did I miss?
You have used:
int x=0;
int y=0;
You need to use:
int x = (int)event.getX();
int y = (int)event.getY();
This one worked,problem was to get right x,y as:
imageView.setOnTouchListener(imgSourceOnTouchListener);
OnTouchListener imgSourceOnTouchListener
= new OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] {eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]);
int y = Integer.valueOf((int)eventXY[1]);
System.out.println(
"touched position: "
+ String.valueOf(eventX) + " / "
+ String.valueOf(eventY));
System.out.println(
"touched position: "
+ String.valueOf(x) + " / "
+ String.valueOf(y));
Drawable imgDrawable = ((ImageView)view).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
System.out.println(
"drawable size: "
+ String.valueOf(bitmap.getWidth()) + " / "
+ String.valueOf(bitmap.getHeight()));
//Limit x, y range within bitmap
if(x < 0){
x = 0;
}else if(x > bitmap.getWidth()-1){
x = bitmap.getWidth()-1;
}
if(y < 0){
y = 0;
}else if(y > bitmap.getHeight()-1){
y = bitmap.getHeight()-1;
}
int touchedRGB = bitmap.getPixel(x, y);
System.out.println("touched color: " + "#" + Integer.toHexString(touchedRGB));
return true;
}};
iView_image1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
int color = 0;
try {
color = bmp.getPixel((int) event.getX(), (int) event.getY());
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
} catch (Exception e) {
}
return false;
}
});

Select Text and show meaning as pop up in MUPDF

I am using MUPDF Library and i added features for manual zoom in, zoom out , rating, setting brightness. Now i am doing with long press the highlighted text and i have to show the meaning from my database. I am trying to do with two things one is clipboard or emulateShiftHeld the below feature is for only android ICS and JellyBean. Can any body suggest on whether any one thing will work for this feature what i am trying. Because on Long Press i can't able to capture the text. Suggestions will be helpful.
This id my MUPDF Activity:
public void createUI(Bundle savedInstanceState) {
if (core == null)
return;
// Now create the UI.
// First create the document view making use of the ReaderView's internal
// gesture recognition
mDocView = new ReaderView(this) {
private boolean showButtonsDisabled;
public void onLongPress(MotionEvent e) {
selectAndCopyText();
//mDocView.getSelectedItem();
//SelectText(mDocView);
/*emulateShiftHeld(layout);
clipboard =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(clipboard.getText().toString());
//layout.findAll(clipboard.getText().toString());
//ClipMan.setPrimaryClip(clipboard);
//String s = (String) clipboard.getText();
//System.out.println("fsfasd"+ s);
CharSequence pasteData="";
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
pasteData = item.getText();
System.out.println("fsf"+pasteData);*/
//ClipData data = ClipData.newPlainText("", "");
///System.out.println("sdf" + data);
//copyClipboard();
}
#SuppressWarnings("deprecation")
public void selectAndCopyText() {
try {
Method m = WebView.class.getMethod("emulateShiftHeld", Boolean.TYPE);
m.invoke(mDocView, false);
} catch (Exception e) {
e.printStackTrace();
// fallback
KeyEvent shiftPressEvent = new KeyEvent(0,0,
KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
shiftPressEvent.dispatch(this);
}
}
public void startTextSelection() {
try {
WebView.class.getMethod("selectText").invoke(this);
} catch (Exception e) {
try {
WebView.class.getMethod("emulateShiftHeld").invoke(this);
} catch (Exception e1) {
KeyEvent shiftPressEvent = new KeyEvent(0, 0,
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(this);
Toast.makeText(getContext(), R.string.app_name, Toast.LENGTH_LONG).show();
}
}
}
// Stick the document view and the buttons overlay into a parent view
//Embedding my reader view to webview
layout = new WebView(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
layout.setBackgroundResource(R.drawable.tiled_background);
//layout.setBackgroundResource(R.color.canvas);
setContentView(layout);
}
This is my Reader View:
public class ReaderView extends AdapterView<Adapter>
implements GestureDetector.OnGestureListener,
ScaleGestureDetector.OnScaleGestureListener,
Runnable {
private static final int MOVING_DIAGONALLY = 0;
private static final int MOVING_LEFT = 1;
private static final int MOVING_RIGHT = 2;
private static final int MOVING_UP = 3;
private static final int MOVING_DOWN = 4;
private static final int FLING_MARGIN = 100;
private static final int GAP = 20;
private static final int SCROLL_SPEED = 2;
private static final float MIN_SCALE = 1.0f;
private static final float MAX_SCALE = 5.0f;
private Adapter mAdapter;
private int mCurrent; // Adapter's index for the current view
private boolean mResetLayout;
private final SparseArray<View>
mChildViews = new SparseArray<View>(3);
// Shadows the children of the adapter view
// but with more sensible indexing
private final LinkedList<View>
mViewCache = new LinkedList<View>();
private boolean mUserInteracting; // Whether the user is interacting
private boolean mScaling; // Whether the user is currently pinch zooming
private float mScale = 1.0f;
private int mXScroll; // Scroll amounts recorded from events.
private int mYScroll; // and then accounted for in onLayout
private final GestureDetector
mGestureDetector;
private final ScaleGestureDetector
mScaleGestureDetector;
private final Scroller mScroller;
private int mScrollerLastX;
private int mScrollerLastY;
private boolean mScrollDisabled;
public ReaderView(Context context) {
super(context);
mGestureDetector = new GestureDetector(this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mScroller = new Scroller(context);
}
public ReaderView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mScroller = new Scroller(context);
}
public ReaderView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mGestureDetector = new GestureDetector(this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mScroller = new Scroller(context);
}
public int getDisplayedViewIndex(ToggleButton bookmark_page, String index_from) {
if (index_from.equals("bookmark_button")) { System.out.println("View_if" + index_from);
bookmark_page.setBackgroundResource(R.drawable.top3hover);
} else { System.out.println("View_else" + index_from);
bookmark_page.setBackgroundResource(R.drawable.top3);
}
return mCurrent;
}
public void setDisplayedViewIndex(int i) {
if (0 <= i && i < mAdapter.getCount()) {
mCurrent = i;
onMoveToChild(i);
mResetLayout = true;
requestLayout();
}
}
public void moveToNext() {
View v = mChildViews.get(mCurrent+1);
if (v != null)
slideViewOntoScreen(v);
}
public void moveToPrevious() {
View v = mChildViews.get(mCurrent-1);
if (v != null)
slideViewOntoScreen(v);
}
public void resetupChildren() {
for (int i = 0; i < mChildViews.size(); i++)
onChildSetup(mChildViews.keyAt(i), mChildViews.valueAt(i));
}
protected void onChildSetup(int i, View v) {}
protected void onMoveToChild(int i) {}
protected void onSettle(View v) {};
protected void onUnsettle(View v) {};
protected void onNotInUse(View v) {};
public View getDisplayedView() {
return mChildViews.get(mCurrent);
}
public void run() {
if (!mScroller.isFinished()) {
mScroller.computeScrollOffset();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
mXScroll += x - mScrollerLastX;
mYScroll += y - mScrollerLastY;
mScrollerLastX = x;
mScrollerLastY = y;
requestLayout();
post(this);
}
else if (!mUserInteracting) {
// End of an inertial scroll and the user is not interacting.
// The layout is stable
View v = mChildViews.get(mCurrent);
postSettle(v);
}
}
public boolean onDown(MotionEvent arg0) {
mScroller.forceFinished(true);
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (mScrollDisabled)
return true;
View v = mChildViews.get(mCurrent);
if (v != null) {
Rect bounds = getScrollBounds(v);
switch(directionOfTravel(velocityX, velocityY)) {
case MOVING_LEFT:
if (bounds.left >= 0) {
// Fling off to the left bring next view onto screen
View vl = mChildViews.get(mCurrent+1);
if (vl != null) {
slideViewOntoScreen(vl);
return true;
}
}
break;
case MOVING_RIGHT:
if (bounds.right <= 0) {
// Fling off to the right bring previous view onto screen
View vr = mChildViews.get(mCurrent-1);
if (vr != null) {
slideViewOntoScreen(vr);
return true;
}
}
break;
}
mScrollerLastX = mScrollerLastY = 0;
// If the page has been dragged out of bounds then we want to spring back
// nicely. fling jumps back into bounds instantly, so we don't want to use
// fling in that case. On the other hand, we don't want to forgo a fling
// just because of a slightly off-angle drag taking us out of bounds other
// than in the direction of the drag, so we test for out of bounds only
// in the direction of travel.
//
// Also don't fling if out of bounds in any direction by more than fling
// margin
Rect expandedBounds = new Rect(bounds);
expandedBounds.inset(-FLING_MARGIN, -FLING_MARGIN);
if(withinBoundsInDirectionOfTravel(bounds, velocityX, velocityY)
&& expandedBounds.contains(0, 0)) {
mScroller.fling(0, 0, (int)velocityX, (int)velocityY, bounds.left, bounds.right, bounds.top, bounds.bottom);
post(this);
}
}
return true;
}
public void onLongPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
if (!mScrollDisabled) {
mXScroll -= distanceX;
mYScroll -= distanceY;
requestLayout();
}
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
public boolean onScale(ScaleGestureDetector detector) {
float previousScale = mScale;
mScale = Math.min(Math.max(mScale * detector.getScaleFactor(), MIN_SCALE), MAX_SCALE);
float factor = mScale/previousScale;
View v = mChildViews.get(mCurrent);
if (v != null) {
// Work out the focus point relative to the view top left
int viewFocusX = (int)detector.getFocusX() - (v.getLeft() + mXScroll);
int viewFocusY = (int)detector.getFocusY() - (v.getTop() + mYScroll);
// Scroll to maintain the focus point
mXScroll += viewFocusX - viewFocusX * factor;
mYScroll += viewFocusY - viewFocusY * factor;
requestLayout();
}
return true;
}
public boolean onScaleBegin(ScaleGestureDetector detector) {
mScaling = true;
// Ignore any scroll amounts yet to be accounted for: the
// screen is not showing the effect of them, so they can
// only confuse the user
mXScroll = mYScroll = 0;
// Avoid jump at end of scaling by disabling scrolling
// until the next start of gesture
mScrollDisabled = true;
return true;
}
public void onScaleEnd(ScaleGestureDetector detector) {
mScaling = false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//mScaleGestureDetector.onTouchEvent(event);
if (!mScaling)
mGestureDetector.onTouchEvent(event);
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
mUserInteracting = true;
}
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
mScrollDisabled = false;
mUserInteracting = false;
View v = mChildViews.get(mCurrent);
if (v != null) {
if (mScroller.isFinished()) {
// If, at the end of user interaction, there is no
// current inertial scroll in operation then animate
// the view onto screen if necessary
slideViewOntoScreen(v);
}
if (mScroller.isFinished()) {
// If still there is no inertial scroll in operation
// then the layout is stable
postSettle(v);
}
}
}
requestLayout();
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int n = getChildCount();
for (int i = 0; i < n; i++)
measureView(getChildAt(i));
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
View cv = mChildViews.get(mCurrent);
Point cvOffset;
if (!mResetLayout) {
// Move to next or previous if current is sufficiently off center
if (cv != null) {
cvOffset = subScreenSizeOffset(cv);
// cv.getRight() may be out of date with the current scale
// so add left to the measured width for the correct position
if (cv.getLeft() + cv.getMeasuredWidth() + cvOffset.x + GAP/2 + mXScroll < getWidth()/2 && mCurrent + 1 < mAdapter.getCount()) {
postUnsettle(cv);
// post to invoke test for end of animation
// where we must set hq area for the new current view
post(this);
mCurrent++;
onMoveToChild(mCurrent);
}
if (cv.getLeft() - cvOffset.x - GAP/2 + mXScroll >= getWidth()/2 && mCurrent > 0) {
postUnsettle(cv);
// post to invoke test for end of animation
// where we must set hq area for the new current view
post(this);
mCurrent--;
onMoveToChild(mCurrent);
}
}
// Remove not needed children and hold them for reuse
int numChildren = mChildViews.size();
int childIndices[] = new int[numChildren];
for (int i = 0; i < numChildren; i++)
childIndices[i] = mChildViews.keyAt(i);
for (int i = 0; i < numChildren; i++) {
int ai = childIndices[i];
if (ai < mCurrent - 1 || ai > mCurrent + 1) {
View v = mChildViews.get(ai);
onNotInUse(v);
mViewCache.add(v);
removeViewInLayout(v);
mChildViews.remove(ai);
}
}
} else {
mResetLayout = false;
mXScroll = mYScroll = 0;
// Remove all children and hold them for reuse
int numChildren = mChildViews.size();
for (int i = 0; i < numChildren; i++) {
View v = mChildViews.valueAt(i);
onNotInUse(v);
mViewCache.add(v);
removeViewInLayout(v);
}
mChildViews.clear();
// post to ensure generation of hq area
post(this);
}
// Ensure current view is present
int cvLeft, cvRight, cvTop, cvBottom;
boolean notPresent = (mChildViews.get(mCurrent) == null);
cv = getOrCreateChild(mCurrent);
// When the view is sub-screen-size in either dimension we
// offset it to center within the screen area, and to keep
// the views spaced out
cvOffset = subScreenSizeOffset(cv);
if (notPresent) {
//Main item not already present. Just place it top left
cvLeft = cvOffset.x;
cvTop = cvOffset.y;
} else {
// Main item already present. Adjust by scroll offsets
cvLeft = cv.getLeft() + mXScroll;
cvTop = cv.getTop() + mYScroll;
}
// Scroll values have been accounted for
mXScroll = mYScroll = 0;
cvRight = cvLeft + cv.getMeasuredWidth();
cvBottom = cvTop + cv.getMeasuredHeight();
if (!mUserInteracting && mScroller.isFinished()) {
Point corr = getCorrection(getScrollBounds(cvLeft, cvTop, cvRight, cvBottom));
cvRight += corr.x;
cvLeft += corr.x;
cvTop += corr.y;
cvBottom += corr.y;
} else if (cv.getMeasuredHeight() <= getHeight()) {
// When the current view is as small as the screen in height, clamp
// it vertically
Point corr = getCorrection(getScrollBounds(cvLeft, cvTop, cvRight, cvBottom));
cvTop += corr.y;
cvBottom += corr.y;
}
cv.layout(cvLeft, cvTop, cvRight, cvBottom);
if (mCurrent > 0) {
View lv = getOrCreateChild(mCurrent - 1);
Point leftOffset = subScreenSizeOffset(lv);
int gap = leftOffset.x + GAP + cvOffset.x;
lv.layout(cvLeft - lv.getMeasuredWidth() - gap,
(cvBottom + cvTop - lv.getMeasuredHeight())/2,
cvLeft - gap,
(cvBottom + cvTop + lv.getMeasuredHeight())/2);
}
if (mCurrent + 1 < mAdapter.getCount()) {
View rv = getOrCreateChild(mCurrent + 1);
Point rightOffset = subScreenSizeOffset(rv);
int gap = cvOffset.x + GAP + rightOffset.x;
rv.layout(cvRight + gap,
(cvBottom + cvTop - rv.getMeasuredHeight())/2,
cvRight + rv.getMeasuredWidth() + gap,
(cvBottom + cvTop + rv.getMeasuredHeight())/2);
}
invalidate();
}
#Override
public Adapter getAdapter() {
return mAdapter;
}
#Override
public View getSelectedView() {
throw new UnsupportedOperationException("Not supported");
}
#Override
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
mChildViews.clear();
removeAllViewsInLayout();
requestLayout();
}
#Override
public void setSelection(int arg0) {
throw new UnsupportedOperationException("Not supported");
}
private View getCached() {
if (mViewCache.size() == 0)
return null;
else
return mViewCache.removeFirst();
}
private View getOrCreateChild(int i) {
View v = mChildViews.get(i);
if (v == null) {
v = mAdapter.getView(i, getCached(), this);
addAndMeasureChild(i, v);
}
onChildSetup(i, v);
return v;
}
private void addAndMeasureChild(int i, View v) {
LayoutParams params = v.getLayoutParams();
if (params == null) {
params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
addViewInLayout(v, 0, params, true);
mChildViews.append(i, v); // Record the view against it's adapter index
measureView(v);
}
private void measureView(View v) {
// See what size the view wants to be
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
// Work out a scale that will fit it to this view
float scale = Math.min((float)getWidth()/(float)v.getMeasuredWidth(),
(float)getHeight()/(float)v.getMeasuredHeight());
// Use the fitting values scaled by our current scale factor
v.measure(View.MeasureSpec.EXACTLY | (int)(v.getMeasuredWidth()*scale*mScale),
View.MeasureSpec.EXACTLY | (int)(v.getMeasuredHeight()*scale*mScale));
}
private Rect getScrollBounds(int left, int top, int right, int bottom) {
int xmin = getWidth() - right;
int xmax = -left;
int ymin = getHeight() - bottom;
int ymax = -top;
// In either dimension, if view smaller than screen then
// constrain it to be central
if (xmin > xmax) xmin = xmax = (xmin + xmax)/2;
if (ymin > ymax) ymin = ymax = (ymin + ymax)/2;
return new Rect(xmin, ymin, xmax, ymax);
}
private Rect getScrollBounds(View v) {
// There can be scroll amounts not yet accounted for in
// onLayout, so add mXScroll and mYScroll to the current
// positions when calculating the bounds.
return getScrollBounds(v.getLeft() + mXScroll,
v.getTop() + mYScroll,
v.getLeft() + v.getMeasuredWidth() + mXScroll,
v.getTop() + v.getMeasuredHeight() + mYScroll);
}
private Point getCorrection(Rect bounds) {
return new Point(Math.min(Math.max(0,bounds.left),bounds.right),
Math.min(Math.max(0,bounds.top),bounds.bottom));
}
private void postSettle(final View v) {
// onSettle and onUnsettle are posted so that the calls
// wont be executed until after the system has performed
// layout.
post (new Runnable() {
public void run () {
onSettle(v);
}
});
}
private void postUnsettle(final View v) {
post (new Runnable() {
public void run () {
onUnsettle(v);
}
});
}
private void slideViewOntoScreen(View v) {
Point corr = getCorrection(getScrollBounds(v));
if (corr.x != 0 || corr.y != 0) {
mScrollerLastX = mScrollerLastY = 0;
mScroller.startScroll(0, 0, corr.x, corr.y, 400);
post(this);
}
}
private Point subScreenSizeOffset(View v) {
return new Point(Math.max((getWidth() - v.getMeasuredWidth())/2, 0),
Math.max((getHeight() - v.getMeasuredHeight())/2, 0));
}
private static int directionOfTravel(float vx, float vy) {
if (Math.abs(vx) > 2 * Math.abs(vy))
return (vx > 0) ? MOVING_RIGHT : MOVING_LEFT;
else if (Math.abs(vy) > 2 * Math.abs(vx))
return (vy > 0) ? MOVING_DOWN : MOVING_UP;
else
return MOVING_DIAGONALLY;
}
private static boolean withinBoundsInDirectionOfTravel(Rect bounds, float vx, float vy) {
switch (directionOfTravel(vx, vy)) {
case MOVING_DIAGONALLY: return bounds.contains(0, 0);
case MOVING_LEFT: return bounds.left <= 0;
case MOVING_RIGHT: return bounds.right >= 0;
case MOVING_UP: return bounds.top <= 0;
case MOVING_DOWN: return bounds.bottom >= 0;
default: throw new NoSuchElementException();
}
}
}
In Reader Class, make localbroadcast and implement it in your main Activity
public void onLongPress(MotionEvent e) {
Intent next = new Intent(StringConstant.SEARCH_WORD);
next.putExtra(StringConstant.DOUBLE_TAP_PDF, "true");
LocalBroadcastManager.getInstance(mContext).sendBroadcast(next);
}
This is your broadcast reciever
private BroadcastReceiver mPdfDoubleClickedReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
Log.e("", "mPdfDoubleClickedReciever called");
hideEditedNotes();
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
boolean success = false;
if (pageView != null)
success = pageView.copySelection();
mTopBarMode = TopBarMode.Main;
// showInfo(success ?
// getString(R.string.copied_to_clipboard)
// : getString(R.string.no_text_selected));
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
selectedClipboardText = "";
selectedClipboardText = (String) clipboard.getText();
// Do task here
}
}
};

Customs views and TouchEvent

I'm programming a custom view that divides the image into pieces. The objective is to exchange the chunk touched by the adjacent piece depending on the displacement direction. The problem I have is that the ACTION_UP of the function OnTouch is never executed. What am I doing wrong?
public class ChunkView extends View implements OnTouchListener {
protected enum MoveDir {
LEFT,
RIGHT,
UP,
DOWN,
NONE
}
//ImageView myImageView;
Bitmap myBitmap;
Paint myPaint;
Paint myRectPaint;
int nRows = 6;
int nCols = 5;
int widthChunk;
int heightChunk;
int idImage;
int showGrid;
float coordX1, coordY1, coordX2, coordY2;
int cellX1, cellY1, cellX2, cellY2;
public int getShowGrid() {
return showGrid;
}
public void setShowGrid(int showGrid) {
this.showGrid = showGrid;
invalidate();
requestLayout();
}
ArrayList<Bitmap> chunksBitmap;
public ChunkView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ChunkView, 0, 0);
try {
showGrid = a.getInteger(R.styleable.ChunkView_showGrid, 0);
}
finally {
a.recycle();
}
setOnTouchListener(this);
init();
// TODO Auto-generated constructor stub
}
public int getIdImage() {
return idImage;
}
public void setIdImage(int idImage) {
this.idImage = idImage;
}
private void init() {
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ejemplo);
//myImageView.setImageBitmap(myBitmap);
myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
myRectPaint = new Paint();
chunksBitmap = new ArrayList<Bitmap>();
myRectPaint.setStyle(Paint.Style.STROKE);
myRectPaint.setColor(Color.BLACK);
myRectPaint.setStrokeWidth(3);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//myImageView.draw(canvas);
for (int r = 0; r < nRows; ++r) {
for (int c = 0; c < nCols; ++c) {
canvas.drawBitmap(chunksBitmap.get(r * nCols + c), widthChunk * c, heightChunk * r, myPaint);
canvas.drawRect(widthChunk * c, heightChunk * r, widthChunk * (c + 1), heightChunk * (r + 1), myRectPaint);
}
}
}
#Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
super.onSizeChanged(xNew, yNew, xOld, yOld);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, xNew, yNew, true);
widthChunk = xNew / nCols;
heightChunk = yNew / nRows;
chunksBitmap.clear();
for (int r = 0; r < nRows; ++r) {
for (int c = 0; c < nCols; ++c) {
chunksBitmap.add(Bitmap.createBitmap(scaledBitmap, c * widthChunk, r * heightChunk , widthChunk, heightChunk));
}
}
}
protected MoveDir getDirection() {
float dx = coordX2 - coordX1;
float dy = coordY2 - coordY1;
if(Math.abs(dx) > Math.abs(dy)) {
if (dx > widthChunk)
return MoveDir.RIGHT;
else if (dx < -widthChunk)
return MoveDir.LEFT;
}
else {
if (dy > heightChunk)
return MoveDir.DOWN;
else if (dy < -heightChunk)
return MoveDir.UP;
}
return MoveDir.NONE;
}
protected boolean isValidCell(int X, int Y) {
return (X >= 0) && (X > nCols) && (Y>= 0) && (Y < nRows);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
String msg = String.valueOf(v.getId());
Log.e("DBG", msg);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.e("DBG", "DOWN");
coordX1 = event.getX();
coordY1 = event.getY();
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
Log.e("DBG", "UP");
coordX2 = event.getX();
coordY2 = event.getY();
MoveDir dir = getDirection();
if (dir != MoveDir.NONE) {
// Converteix els pixels en coordenades
cellX1 = cellX2 = ((int)(coordX1 / widthChunk) * widthChunk);
cellY1 = cellY2 = ((int)(coordY1 / heightChunk) * heightChunk);
if (dir == MoveDir.LEFT)
cellX2--;
else if (dir == MoveDir.RIGHT)
cellX2++;
else if (dir == MoveDir.UP)
cellY2--;
else if (dir == MoveDir.UP)
cellY2++;
String msg1 = "(" + String.valueOf(cellX1) + ", " + String.valueOf(cellY1) + ")";
String msg2 = "(" + String.valueOf(cellX2) + ", " + String.valueOf(cellY2) + ")";
Log.e("DBG", msg1 + " -> " + msg2);
if ((!isValidCell(cellX1, cellY1)) || (!isValidCell(cellX2, cellY2)))
return false;
invalidate();
}
}
return false;
}
}
Thanks in advance.
try to use this.. it uses switch case statement so for any time the screen is pressed it will return true, so if the next time you stop pressing the screen it will go the ACTION_UP case
#Override
public boolean onTouch(View v, MotionEvent event) {
String msg = String.valueOf(v.getId());
Log.e("DBG", msg);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e("DBG", "DOWN");
coordX1 = event.getX();
coordY1 = event.getY();
return true;
case MotionEVent.ACTION_UP:
Log.e("DBG", "UP");
coordX2 = event.getX();
coordY2 = event.getY();
// rest of your code
return true;
}

Drag & Drop for older Android not precise

So I'm attempting to make a "magnetic poetry" type application. Users will move various Button widgets on the screen. I am using a Button widget since it is the closest to the look of the magnet, though I am open to other options!
The objects are not properly moving with my finger. They're close but they're not exactly in line with my finger. The X coordinate on my phone seems to be fine, but the Y corrdinate is off. Is this perhaps due to the title bar?
private final static int DRAGGING_OFF = 0;
private final static int DRAGGING_ON = 1;
private int dragStatus;
private GestureDetector mGestureDetector;
private int mOffsetX;
private int mOffsetY;
private LayoutParams mOldParams;
private RelativeLayout.LayoutParams lp;
#Override
public boolean onTouchEvent(MotionEvent event) {
if(!mGestureDetector.onTouchEvent(event)) {
if(event.getAction() == MotionEvent.ACTION_MOVE) {
if(dragStatus == DRAGGING_ON) {
Log.e(VIEW_LOG_TAG, "Dragging! RAW -- " + event.getRawX() + " : " + event.getRawY() + " NOT RAW -- " + event.getX() + " : " + event.getY());
int rawX, rawY;
int finalX, finalY;
rawX = (int) event.getRawX();
rawY = (int) event.getRawY();
finalX = rawX - mOffsetX;
finalY = rawY - mOffsetY;
lp.setMargins(finalX, finalY, 0, 0);
this.setLayoutParams(lp);
}
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP) {
if(dragStatus == DRAGGING_ON) {
dragStatus = DRAGGING_OFF;
Log.e(VIEW_LOG_TAG, "Stopped dragging!");
}
return true;
} else {
return super.onTouchEvent(event);
}
} else {
return true;
}
}
private final GestureDetector.SimpleOnGestureListener mListener = new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onDown(MotionEvent e) {
int[] location = new int[2];
Log.e(VIEW_LOG_TAG, "Down! RAW -- " + e.getRawX() + " : " + e.getRawY() + " NOT RAW -- " + e.getX() + " : " + e.getY());
dragStatus = DRAGGING_ON;
// Sets the current location of the View in the int[] passed to it; x then y.
getLocationInWindow(location);
Log.e(VIEW_LOG_TAG, "Down location: " + location[0] + " " + location[1]);
mOffsetX = (int) e.getRawX() - location[0];
mOffsetY = (int) e.getRawY() - location[1];
mOldParams = getLayoutParams();
return true;
}
};
I think the issue is that you're not getting the DELTA of the current touch point Y and the cached, last touch point y. You need something like this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.text);
final ImageView image = (ImageView) findViewById(R.id.image);
matrix.setTranslate(1f, 1f);
image.setImageMatrix(matrix);
image.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
matrix.getValues(m); //copy matrix values into array
PointF currentXYTouchPoint = new PointF(event.getX(), event.getY());
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN: //start of pressed gesture
lastXYTouchPoint.set(event.getX(), event.getY()); //save the last touchpoint
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
//calculate the change in finger position
float deltaX = currentXYTouchPoint.x - lastXYTouchPoint.x;
float deltaY = currentXYTouchPoint.y - lastXYTouchPoint.y;
matrix.postTranslate(deltaX, deltaY); //move the entire image by the deltas
image.setImageMatrix(matrix);
// save this last starting touchpoint
lastXYTouchPoint.set(currentXYTouchPoint.x, currentXYTouchPoint.y);
break;
}
textView.setText("TouchPoint started at " + currentXYTouchPoint.x + ", " + currentXYTouchPoint.y + " & the matrix is now " + Arrays.toString(m));
return true;
}
});
}
Adapt it to your own purposes, but the basic idea is there.

Categories

Resources