我有一个OnTouch按钮,当单击按钮时会使用运动事件进入下一个活动,但是我希望它仅在单击按钮时保留在Next活动中然后返回...如果是似乎很困惑,这里是代码 - :
@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;
}
});
答案 0 :(得分:1)
在下一个活动的根视图上使用相同的onTouch,并完成激活ACTION_UP
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
finish();
}
return true;
}
});
(更新)经过测试的答案:
第一项活动:
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;
}
}
第二项活动:
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);
}
}
这是有效的