FindfragmentByid在特定活动中返回无效



我正在尝试获取片段的实例,以调用其中的某些功能。不寻常的是,我从getFragmentManager()。findfragmentById(id)函数中获得零。但是,在另一项活动中,我可以使用相同函数getFragmentManager()。findfragmentById(id)。

这是我不工作的活动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);
    }
}

这是活动的不起作用的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>

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

  getSupportFragmentManager() // instead of fragmentManager

so,

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

最新更新