如何将某些函数从活动转换为片段?



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

我的主页活动:

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

有什么想法吗?

您应该用膨胀的视图替换getActivity()呼叫。

以前

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

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

最新更新