Search code examples
androidandroid-fragmentsfragmentandroid-listfragment

Programatically create List Fragment and Fragment


How can we convert the below xml progrmatically

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/list_fragment"
        android:name="com.aaa.bbb.activity.FragmentedListActivity$MyListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#27577f" />

    <fragment
        android:id="@+id/detail_fragment"
        android:name="com.aaa.bbb.activity.FragmentedListActivity$MyDetailFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" />
</LinearLayout>


Solution

  • this may help you...

    private static final int ID_MY_FRAGMENT = 0xDEAF1;
    private static final int ID_MY_DETAIL_FRAGMENT = 0xDEAF2;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View contentView = getView();
        setContentView(contentView);
        getSupportFragmentManager().beginTransaction()
                .replace(ID_MY_FRAGMENT, new MyListFragment())
                .replace(ID_MY_DETAIL_FRAGMENT, new MyDetailFragment()).commit();
    }
    
    private View getView() {
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.HORIZONTAL);
    
        FrameLayout frameLayout = new FrameLayout(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
        frameLayout.setLayoutParams(layoutParams);
        frameLayout.setId(ID_MY_FRAGMENT);
        layout.addView(frameLayout);
    
        View view = new View(this);
        layoutParams = new LinearLayout.LayoutParams((int) (1 * getResources()
                .getDisplayMetrics().density),
                LinearLayout.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(layoutParams);
        view.setBackgroundColor(27555);
        layout.addView(view);
    
        frameLayout = new FrameLayout(this);
        layoutParams = new LinearLayout.LayoutParams(0,
                LinearLayout.LayoutParams.MATCH_PARENT, 2);
        frameLayout.setLayoutParams(layoutParams);
        frameLayout.setId(ID_MY_DETAIL_FRAGMENT);
        layout.addView(frameLayout);
        return layout;
    }