Search code examples
androidformsonclickfocusandroid-linearlayout

Android: Switch loses focus after click


Hey Hey currently I am developing an application that contains a form, with some edittext fields, some checkboxes and a switch at the end. The layout looks like this:

<RelativeLayout>
  <ScrollView>
    <LinearLayout>
       <LinearLayout>
         <TextView></TextView>
         <Checkbox></Checkbox>
       </LinearLayout>
       <LineraLayout>
         <TextView></TextView>
         <EditText></EditText>
       </LinearLayout>
       <LinearLayout>
         <TextView></TextView>
         <Switch></Switch>
       </LinearLayout>
     </LinearLayout>
  </ScrollView>
</RelativeLayout>

So now, if I click the switch, the switch looses its focus and the scrollview scrolls to the first form element, the checkbox. I already tried to use the descendantFocusability attribute with "blocksDescendants" in the upper LinearLayout of the Switch, but it doesn't work.

Anyone got an idea how to solve this issue?


Solution

  • Okay, I was able to fix the problem by myself. I'm posting my solution, so that it could be helpful for other people who might have the same problem.

    In my code there was a specific function, which calls the setVisibility(View.Visible) method for all my form elements (this is used in my project to display possible dependend form elements, that should only show up, when the user clicks on a checkbox or sth else). If I click on the switch or a checkbox my code calls the setVisibility-Method for all the form elements, also for the Edittext. This requests the focus and so the scrollview scroll this element to the middle/focus of the screen. I solved the problem by not calling the setVisibility method for objects, that are already visible.

    Hopefully this could be helpful for someone else ;-)