1

Im relative new to android development. I have create a Fragment that contains views, buttons, constraints etc., i called it fragment_code_activation_circles. Now i want to add it to new fragment, that is suppose to be "main" and contain all of other fragments i did create, and i want to set constraints to it, but i don't know how to add it. From common pallete i tried to drag {}<fragment> to screen on Design tab, but not succeed. Is that possible or probably i do something that i not suppose to do? On iOS you can simply add any child of View class to an parent view and set it constraints easily.

Alon Aviram
  • 190
  • 1
  • 15
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • A fragment is like a "small view block". It can be added or replaced in a container but you can't have 2 nested Fragments because they are simply views. In Android, in the XML editor, only ViewGroup derived widgets can have one or more children – MatPag Mar 11 '19 at 19:06

2 Answers2

1

You cant place activity inside fragment - fragments are only meant to be placed inside an activity.
You can put as many fragments as you want in your activity but you can't put your activity inside the fragment. Think of fragment as a mini activity that can be placed inside the activity.

From the documentation:

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

Now, if you want to have 1 screen that contains fragments you will have to create 1 activity, put your fragments inside and replace them whenever you want to.
To achieve this behavior use the new Navigation Architecture Component.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
0

Check this link Dynamically add fragment into fragment

Also, you might want to consider using a custom view instead of nested fragments, it makes things more re-usable.


class YourCustomView extends FrameLayout {
    public YourCustomView(@NonNull Context context) {
        super(context);
        init();
    }

    public YourCustomView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public YourCustomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        LayoutInflater.from(getContext()).inflate(R.layout.your_layour,this);
    }
}

Then you can just grab views in your layout by calling findViewById() on your custom view

Benoit TH
  • 601
  • 3
  • 12