I have a OnTouch Button,Which while the button is click goes to the next activity using motion event,but I want it to stay in the Next activity only for the time the button is clicked and then return...If it seems to be perplexing ,here is the code-:
@Override
public boolean onTouch(View v, MotionEvent event) {
while (event.getAction() == MotionEvent.ACTION_DOWN){
Intent myIntent = new Intent(MainActivity.this, ActionActivity.class);
myIntent.putExtra("key", value); //Optional parameters
MainActivity.this.startActivity(myIntent);
}
if(event.getAction() == MotionEvent.ACTION_UP){
}
return true;
}
});
Use the same onTouch on root view of the next activity and finish the activty ACTION_UP
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
finish();
}
return true;
}
});
(Update) Tested Answer:
First Activity:
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
viewGroup.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Intent myIntent = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(myIntent);
return true;
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
SecondActivity.activity.get().finish();
return true;
}
return true;
}
}
Second Activity:
public class SecondActivity extends AppCompatActivity {
public static WeakReference<Activity> activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
activity = new WeakReference<Activity>(this);
}
}
This is working