Turns out that the only way to achieve this it to duplicate the header (create 2 instances of the same View
)...
Share View between ListView and ScrollView
-
19-06-2023 - |
Вопрос
I have the following layout:
when I click on Btn 1, the Content will be a ListView
, clicking on Btn 2, will show a LinearLayout
. My problem is that I want the whole thing to scroll. So if my root is a ScrollView
, the content displayed with Btn 2 is fine, but as we know, it ain't working with ListView
.
So instead, my root layout includes 2 layouts:
<RelativeLayout id="root">
<include layout=listViewLayout />
<include layout=scrollViewLayout />
</RelativeLayout>
And the idea is to have a header view:
such that when the root view is created, I inflate the header, set is as header view to the ListView
(working fine), and add it to the ScrollView
. But as soon as I add it (technically, it'a added to a LinearLayout
inside the ScrollView
), then I get the following crash:
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
Technically, I could have two headers doing exactly the same thing (set picture, set listeners to buttons), but for the sake of avoiding duplication, what are the other alternatives?
If I add the header as a row (instead of a using listView.addHeaderView
) and modify my adapter to handle different layouts, will it solve the problem?
Thanks!
EDIT: to clarify, when I click on Btn 1 or 2, I simply show / hide the layouts. I don't dynamically modify the ViewGroup. It allows me to show either the ListView
+ header or the ScrollView
. The exception occurs the first time the root is displayed. But if I don't try to add the header view in the ScrollView
, then it's programmatically working fine.
EDIT 2: sharing 1 header (View
) among 2 ListViews
is not working either. From a UI point of view, it looks ok, but the interaction is not (some buttons stop responding to click).
Also, I can't have only 1 ListView
because the content is pulled from the web, which means I'll have to store / restore everything each time I switch between views.
Решение 2
Другие советы
You should never put a listView inside a scrollView (or the opposite).
You'd better watch the lecture "the world of listView" to learn how you should handle such cases.
One way to handle it is to either have a header for the listView, or create a new viewType for each special row you wish to create.