Dynamically Add Fragment with LayoutParams

Is it possible to add dynamically add Fragments with LayoutParams? I have 2 fragments that I want to put in a RelativeLayout: one should lock to the left. The other should be locked to the right.

Answers


You could wrap them each in a layout (such as a LinearLayout), then set its size and position. This answer is regarding a similar problem, and shows how to use a FrameLayout with custom layout parameters to contain a Fragment.

Note that, when using the fragment object in XML, you can use android:layout_* attributes to control its position. Like so:

<LinearLayout
    android:orientation="horizontal"
    ... >

    <fragment
        android:layout_height="wrap_content"
        android:layout_width="0px"
        android:layout_weight="1"
        ... />

    <fragment
        android:layout_height="wrap_content"
        android:layout_width="0px"
        android:layout_weight="1"
        ... />

</LinearLayout>

However, I don't think it's possible to apply layout parameters programmatically to Fragments. They're not ViewGroups, after all.


I used the following approach for a ListFragment in a LinearLayout:

class CustomListFragment
    extends ListFragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        ViewGroup v = (ViewGroup) super.onCreateView(inflater, container,
                savedInstanceState);
        v.setLayoutParams(new LinearLayout.LayoutParams(0,
                LinearLayout.LayoutParams.MATCH_PARENT, 1));
        return v;
    }
}

Now that I read your comments on the other answer, I see it is similar to what you considered.

But note: the framework may instantiate your fragments. Therefore, the class must be public and must have a constructor without any further arguments.

Any setter-methods to customize your fragments won't work therefore, as they won't be called for any framework-created instances.


Need Your Help

Obtain lock on P4 through Java Code

java perforce

I want to obtain lock on P4 Branch through Java Code. Any one know hoe to achieve it through Java?

c:forEach doesn't render inside rich:dataTable

jsf seam richfaces jstl

I am using c:forEach inside rich:dataTable. But c:forEach doesn't substitute the values for answer.choices variable and hence nothing is rendered. Is it wrong to use c:forEach inside a rich:dataTab...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.