gpt4 book ai didi

java - findFragmentById 在特定 Activity 中返回 null

转载 作者:行者123 更新时间:2023-12-02 10:10:54 24 4
gpt4 key购买 nike

我正在尝试获取 fragment 的实例来调用其中的某些函数。不同寻常的是,我从 getFragmentManager().findFragmentById(id) 函数中获取 null 。但是,在另一个 Activity 中,我可以使用相同的函数 getFragmentManager().findFragmentById(id) 获取 fragment 的实例。

这是我不工作的 Activity java:

public class SetMapActivity extends AppCompatActivity {
public int imageId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_map);
clearSelected(null);

BoardFragment boardFragment = (BoardFragment)getFragmentManager().findFragmentById(R.id.sm_fragment); // It will be null


if(boardFragment.boardPositions.contains(R.drawable.sp)) // Null exception here
findViewById(R.id.sp).setEnabled(false);
if(boardFragment.boardPositions.contains(R.drawable.ep))
findViewById(R.id.ep).setEnabled(false);
}
}

这是 Activity 的无效 xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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.example.user.myapplication.SetMapActivity"
tools:layout_editor_absoluteY="25dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>

<fragment
android:id="@+id/sm_fragment"
android:name="com.example.user.myapplication.BoardFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="@layout/fragment_board"
/>

</LinearLayout>

</android.support.constraint.ConstraintLayout>

最佳答案

我假设您已经为 BoardFragment 扩展了 app.v4.Fragment。因此,对于支持库,您应该使用:-

  getSupportFragmentManager() // instead of fragmentManager

所以,

  BoardFragment boardFragment = (BoardFragment) getSupportFragmentManager().findFragmentById(R.id.sm_fragment);

关于java - findFragmentById 在特定 Activity 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com