When I chose an element from this HorizontalScrollView
, I was setting focus
to that element by calling:
else if (v.getParent() == candidatesScrollView.getChildAt(0))
{
Button candidateButton = (Button) v;
v.requestFocusFromTouch();
v.setSelected(true);
(...)
}
Here is part of my XML:
<HorizontalScrollView
android:id="@+id/CandidatesHorizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/linearLayout2"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:visibility="gone" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:orientation="horizontal" >
<Button
android:id="@+id/horizontalscrollview1_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textSize="25sp" />
(...)
// 11 more buttons
</LinearLayout>
</HorizontalScrollView>
After that, when I scrolled the list without choosing other element, I was losing focus
of previously selected element. I made some research about this topic, but there was no solution that could work for me. Finally, after almost two weeks I have created some solution by myself.
I would like you to review it and tell me what can I improve on.
I created a custom HorizontalScrollView
class inside and have overridden the onTouchEvent()
method. I don't think this is optimal way of doing that, because in that case I have to do calculations every time I move even one pixel. For example, if I add toast.show()
to the below method, it will try to show as many toast
as many I moved pixels (If I move by 10 pixels, it will try to show 10 Toast
). Anyway, it works for me and the selection and focus are being kept. Please help me modify this code to make finally a good answer for that known issue:
@Override
public boolean onTouchEvent(MotionEvent ev)
{
int i = 0;
Button button = null;
for (; i < 11; i++)
{
button = (Button)((LinearLayout)getChildAt(0)).getChildAt(i);
if(button.isSelected())
break;
}
super.onTouchEvent(ev);
button.setSelected(true);
button.requestFocusFromTouch();
return true;
}
To be sure that the above code will work, you need to have only one selected item in your HorizontalScrollView
at a time, i.e when you press different Button
, you need to make the previous one setSelected(false)
.