java—如何将一些函数从活动转换为片段?

w6lpcovy  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(353)

我试图将我的活动转换为一个片段,但出现了一些问题。homefragment中的布局为空,因此发生崩溃。。。
我的家庭活动:

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);
...

我的家庭片段:

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);
...

有什么想法吗?

vs91vp4v

vs91vp4v1#

你应该换掉你的衣服 getActivity() 用你夸张的观点打电话。
之前

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

之后

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

相关问题