1

Does anyone know how to create LinearLayout in Fragment? I would like to display TextView, ListView in a layout, so I would like to create it in a LinearLayout. However, I cannot create the LinearLayout in the class like: LinearLayout ll = new LinearLayout(this);

public class GamesFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_games, container, false); return rootView; }} 

This is my XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ff8400" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Design Games Screen" android:textSize="20dp" android:layout_centerInParent="true"/> 

2
  • Why can't you create your linear layout in the xml file itself instead of doing it programatically? Commented Aug 24, 2014 at 23:35
  • Because I'm not really familiar with XML, is there any way to create it in java code? Commented Aug 24, 2014 at 23:55

1 Answer 1

1

If I understand your question correctly, you want to create a LinearLayout inside your fragment's layout file. If there is no reason to create it programatically, then use the xml file like this:

 <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ff8400" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Design Games Screen" android:textSize="20dp" android:layout_centerInParent="true"/> <ListView android:layout_width="match_parent" android:layout_height="20dp" /> </LinearLayout> 

That way, when you inflate the layout in your fragment, you will have the linear layout in it already defined. I hope this helped.

Sign up to request clarification or add additional context in comments.

5 Comments

Why, oh why, did you keep the RelativeLayout?
Is there anyway to create in java code? @Eenvincible
Sure. You can just do LinearLayout ll = new LinearLayout(getActivity); then add to the root element
May I know how to add into root?
androidexample.com/… updated link with better example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.