I have a scrollView with lot of elements
ScrollView scroller = (ScrollView)findViewById(R.id.scrollView);
I need to attach an onClickListe
The best solution seem to put LinearLayout
into ScrollView
and set the setOnClickListener
on it.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/myLayout"
android:clickable="true"
android:orientation="vertical">
<!-- content here -->
</LinearLayout>
</ScrollView>
in the Activity :
LinearLayout lin = (LinearLayout) fragment.rootView.findViewById(R.id.myLayout);
lin.setOnTouchListener(new setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Whatever
}
});
I think you can custom a ScrollView, override the dispatchTouchEvent method, add add the custom onClick callback.
My problem was somehow different, so I wanted to share it..
I have a ScrollView
that I have to use match_parent
in its width & height; and I have an internal TextView
that is centered in the ScrollView
.
The text of the TextView
can be long so it occupies the full height of the ScrollView
, and sometimes it can be short, so there will be blank areas on the top and bottom., So setting the OnClickListener
on the TextView
didn't help me whenever the text is short as I want the blank areas detects the click event as well; and also the OnClickListener
on the ScrollView
doesn't work..
So, I solved this by setting OnTouchListener
on the ScrollView
and put code into MotionEvent.ACTION_UP
So it can kind of simulating complete tap by lefting off the finger off the screen.
private View.OnTouchListener mScrollViewTouchListener = new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// DO Something HERE...
}
return false;
}
};
It is because the child of the ScrollView
is getting the touch event of the user and not the ScrollView
. You must set the clickable=false attribute to each and every child of the ScrollView
for the onClickListener
to work on ScrollView
.
Or else the alternate could be to set the onClickListener
on each of the ScrollView's children and handle it.
You need to set the setOnClickListener
directly on the ScrollView's child.
Since a ScrollView can have only one child, you can simply use this approach:
ScrollView scrollView = //...
View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
// ...
}
//Set the onClickListener directly on the ScrollView's child
scrollView.getChildAt(0).setOnClickListener(mOnClickListener);