Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Fragments: setContentView alternative

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?

like image 417
leshka Avatar asked Aug 04 '11 08:08

leshka


People also ask

What are the methods you can override in the fragment class?

The Fragment class has two callback methods, onAttach() and onDetach() , that you can override to perform work when either of these events occur.

What does the onCreateView () method return if a fragment doesn't have any UI?

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.

What is retained fragment in Android?

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.

What is an android fragment?

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.


2 Answers

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); 
}
like image 148
ASH Avatar answered Oct 06 '22 11:10

ASH


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);
}
like image 41
inazaruk Avatar answered Oct 06 '22 11:10

inazaruk