我尝试将我的活动转换为片段,但是出现了一些问题。
HomeFragment中的布局为null,因此会发生崩溃...

我的家庭活动:

public class HomeActivity extends AppCompatActivity  {
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    //the layout on which you are working
    ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.homeContainer);

    final ConstraintLayout layout2 = (ConstraintLayout) findViewById(R.id.homeContainer);
    ViewTreeObserver vto = layout2.getViewTreeObserver();
    vto.addOnGlobalLayoutListener (new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
...


我的HomeFragment:

public class HomeFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.activity_home, container, false);

        //the layout on which you are working
        ConstraintLayout layout = (ConstraintLayout) getActivity().findViewById(R.id.homeContainer);

        final ConstraintLayout layout2 = (ConstraintLayout) getActivity().findViewById(R.id.homeContainer);
        ViewTreeObserver vto = layout2.getViewTreeObserver();
        vto.addOnGlobalLayoutListener (new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                 layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
...


有任何想法吗?

最佳答案

您应该用展开视图替换getActivity()调用。

之前

ConstraintLayout layout = (ConstraintLayout) getActivity().findViewById(R.id.homeContainer);




ConstraintLayout layout = (ConstraintLayout) view.findViewById(R.id.homeContainer);

08-18 18:19