I'm trying to rewrite an existing project using fragments
to port my application on tablet.
I'm replacing activities with fragments
.
The problem is that I don't know what is the equivalent to setContentView
method? Is there any way to create Fragment's
view except rewriting onCreateView
?
The Fragment class has two callback methods, onAttach() and onDetach() , that you can override to perform work when either of these events occur.
These files contain only the onCreateView() method to inflate the UI of the fragment and returns the root of the fragment layout. If the fragment does not have any UI, it will return null.
A Fragment represents a reusable portion of your app's User Interface. Retained Fragment consists of the configuration change that causes the underlying Activity to be destroyed. The term "retained" refers to the fragment that will not be destroyed on configuration changes.
According to the Android documentation, a fragment is a part of applications user interface that is bound to an activity. Fragments have their lifecycle and layouts or UI components. Fragments help enrich your UI design, pass data between different screens, and adapt to different device configurations.
In the onCreateView()
method you can return the view of your fragment as follows :
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ads_tab, container, false);
}
I'm not sure why you cannot use onCreateView
. But here is what you can do.
Create LinearLayout
object, save it as mRooLayout
member field and return it from onCreateView
. Here is how you can implement setContentView
:
void setFragmentContentView(View view)
{
LinearLayout.LayoutParams layoutParams =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
mRootLayout.removeAllViews();
mRootLayout.addView(view, layoutParams);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With