Search code examples
javaandroidandroid-intent

startActivityForResults interferes with onTouchListener


I am new to Java programming but have programmed in other languages. I am having an issue with what I think is losing view focus when returning from a new intent.

The first time I run I want to collect information from the user, so I do

Intent myIntent = new Intent(getApplicationContext(), UserInformation.class);
startActivityForResult(myIntent, UserInformationRequest);

This works fine. I jump to the intent, collect the data and return to onActivityResult. There I want to display the main screen and have the user move an image around, so I setup an onTouchListener

 @Override
  public void onActivityResult(int iRequestCode, int iResultCode, Intent UserInformationData)
   {
    super.onActivityResult(iRequestCode, iResultCode, UserInformationData); 
    
    switch(iRequestCode)
     {
      case UserInformationRequest: setContentView(R.layout.main);
                                   doMoving();                                 
     }
   }


  public void doMoving()
    {
       ivImage =(ImageView) findViewById(R.id.image);
       ivImage.setOnTouchListener(this);  
   }
  
  
  @Override
  public boolean onTouch(View View, MotionEvent event)
   {
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    
    switch (event.getAction() & MotionEvent.ACTION_MASK)
     {
      case MotionEvent.ACTION_DOWN: _xDelta = (int) (X - ivImage.getTranslationX());
                                    _yDelta = (int) (Y - ivImage.getTranslationY());
                                    
                                    ivHomeImage.setVisibility(View.VISIBLE);
      break;
   
      case MotionEvent.ACTION_UP: ivHomeImage.setVisibility(View.INVISIBLE);
      break;
   
      case MotionEvent.ACTION_POINTER_DOWN:
      break;
   
      case MotionEvent.ACTION_POINTER_UP:
      break;
    
      case MotionEvent.ACTION_MOVE: ivImage.setTranslationX(X - _xDelta);
                                    ivImage.setTranslationY(Y - _yDelta);
      break;
     }
    return true;
   }
 }

This does not work. If I skip calling the intent and go directly to the onTouchListener the image can be moved.

I do understand why calling the Intent and returning leaves my MainActivity broken.


Solution

  • You are using setcontentview twice. Doing so will require you to initialize most of the things like buttons,etc again. Its not a good practice. It is recommended to use only once and in onCreate method of your activity. Remove this line:

    setContentView(R.layout.main);//on onActivityResult