The app I'm building has a use case in which, based on some data I create sections in a Fragment
. To visualize, a given fragment A has a layout with main container element being ScrollView
. There, the scroll view has a toolbar (irrelevant for this question) and then ConstraintLayout
(showing all the fragment's content, lets call it masterLayout
). What I need to be able to do is to, based on a boolean
(let's call it hasSection
) remove a view component from masterLayout
. Therefore, sometimes fragment A will show masterLayout
(which is NOT at position 0 in the container - it is 5th component in the view tree) and sometimes it will not. Now, I tried to simply calling:
((ViewGroup)masterLayout.getParent()).removeView(masterLayout);
which works partially. The problem here is, the view is removed, but the space it occupied is not. Therefore, any other children appearing after that view in the view tree will not be "moved up". I can't leave it like that, as the masterLayout
has height = 200dp. As you can see, it will occupy a significant portion of the screen. Therefore, after researching the web, I found the solution to set its visibility:
masterLayout.setVisibility(View.GONE);
which works as intended. The view is removed, all further child views are moved up accordingly so there is no empty and unwanted space. The problem is that when I do transition away from that fragment (lets say there is a clickable view which takes the user to a different fragment) and come back to it again (for example using back button with onBackPressed
()), masterLayout
that has been set to visibility = View.GONE
will not show up anymore.
How can I achieve the functionality of removing/hiding a particular view from a layout, with having the next views beneath it moved up to cover empty space (like View.GONE
does) while restoring the original layout when navigating back to described fragment?
Full code of the logic:
if(isTypeA){
new FetchUser(USERID){
@Override
protected void onPostExecute(User user){
mUser = user;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new FetchImages(mUser.getType()){
@Override
protected void onPostExecute(List<Image> result){
if(mImageList.isEmpty() && !result.isEmpty()){
mImageList.addAll(result);
mAdapter = new ItemAdapter(getChildFragmentManager(), mImageList.size(), mImageList);
mItemCardPager.setAdapter(mAdapter);
}else{
if(mMasterLayout != null){
mMasterLayout.setVisibility(View.GONE);
}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}