Reputation: 1120
I know there are a lot of setVisibility()
questions on here but I can't find any about this specific case.
When I set the visibility in onCreatView():
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.parentfragment, container, false);
View childView = view.findViewById(R.id.child_View)
if(routingIsOn)childView.setVisibility(View.VISIBLE)
else childView.setVisibility(View.GONE)
return view;
}
It doesn't change anything. (I have hard coded the routingIsOn value as both true and false and either way it doesn't affect the view's visibility.
However interestingly if I run the setVisibility()
code in a delayed runnable on the main thread it does update the UI as expected. But this feels really hacky.
So is there a non-hacky way to change the visibility when the fragment is being created?
Here is the parent xml:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.salesrabbit.android.sales.universal.canvass.map.MapContainerFragment">
<FrameLayout
android:id="@+id/map_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:id="@+id/route_header_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@+id/area_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
Upvotes: 0
Views: 588
Reputation: 54234
Usually, when something like this is happening, it is because the Android framework is automatically saving and restoring view state for you. I didn't think that visibility was part of the saved state, but maybe it is.
During onCreateView()
, this state has not yet been restored, so anything you change that will later be restored will just be overwritten. You have to make your changes after the view state has been restored, and the callback to do that in is onViewStateRestored()
. Try this:
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
View childView = getView().findViewById(R.id.child_View);
if (routingIsOn) {
childView.setVisibility(View.VISIBLE);
} else {
childView.setVisibility(View.GONE);
}
}
Upvotes: 2
Reputation: 349
You should use
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
val childView = view.findViewById(R.id.child_View)
if(routingIsOn)childView.setVisibility(View.VISIBLE)
else childView.setVisibility(View.GONE)
super.onViewCreated(view, savedInstanceState)
}
Upvotes: 3