Tester2389
Tester2389

Reputation: 159

Get ConstraintLayout in a Fragment

Good Daay,

I'd like to get a ConstraintLayout in a Fragment, however when debugging it priints this error `

java.lang.NullPointerException: Attempt to invoke virtual method 'int androidx.constraintlayout.widget.ConstraintLayout.getChildCount()' on a null object reference

on this line

constraintSet.clone(constraintLayout);

So here are my activity used for the fragment and below the code of the fragment

fragment_activity:

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.something.fragments.Fragment"
    android:id="@+id/this_fragment">

...



</androidx.constraintlayout.widget.ConstraintLayout>

And here my code:

public class Fragment extends AppCompatDialogFragment {

View view;

@SuppressLint("InflateParams")
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()), R.style.Some_Theme_Name);
    LayoutInflater inflater = getActivity().getLayoutInflater();
    view = inflater.inflate(R.layout.fragment_activity, null);

    ConstraintLayout constraintLayout = getActivity().findViewById(R.id.this_fragment);
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);


    return builder.create();
}

}

Help would be really appreciated

Upvotes: 1

Views: 1794

Answers (1)

Yunus Kulyyev
Yunus Kulyyev

Reputation: 1022

Try this way:

    ConstraintLayout constraintLayout = view.findViewById(R.id.this_fragment);
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);

Upvotes: 1

Related Questions