问题
I try to scroll to specific point when the user click on edittext, so added the following code to listen to click and focus on this edittext:
et_email = (EditText) view.findViewById(R.id.editEmail);
//bring to center of screen when clicked / focused
et_email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ScrollView scrollView = (ScrollView)getView().findViewById(R.id.ScrollViewSendDetails);
scrollView.smoothScrollTo(0, 500);
}
});
et_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
ScrollView scrollView = (ScrollView) getView().findViewById(R.id.ScrollViewSendDetails);
scrollView.smoothScrollTo(0, 500);
}
});
The problem is that the scrolling works only after the second click. In the first click on the edittext nothing happens
回答1:
Why do you have to listener for the same? Try to use an onTouch listener:
et_email.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
ScrollView scrollView = (ScrollView)getView().findViewById(R.id.ScrollViewSendDetails);
scrollView.smoothScrollTo(0, 500);
}
return false;
}
});
回答2:
Maybe a bit late but whoever is interested in a solution: replacing
scrollView.smoothScrollTo(0, 500)
with
scrollView.postDelayed(() -> scrollView.smoothScrollTo(0, 500), 200);
worked for me.
来源:https://stackoverflow.com/questions/34290504/scrollto-after-focus-onclick-event-works-only-after-second-click