安卓开发Fragment无法得到控件


 
public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment(),"root")
                    .commit();
        }

    }
    @Override
    protected void onStart() {
        super.onStart();
        Fragment RootFragment = getSupportFragmentManager().findFragmentByTag("root");
        assert RootFragment != null;
        View root_view = RootFragment.getView();
        assert root_view != null;
        CheckBox checkBox_have_authorized = findViewById(R.id.have_authorized);
        if (checkBox_have_authorized!= null)
            checkBox_have_authorized.setOnCheckedChangeListener(new CbxHaveAuthorizedListener());
        else
            Log.e("find error","checkBox_have_authorized is null");

    }
    class CbxHaveAuthorizedListener implements CompoundButton.OnCheckedChangeListener
    {
        @Override
        public void onCheckedChanged(CompoundButton button,boolean checked) {
            Toast.makeText(getApplicationContext(), "按钮被点击了", Toast.LENGTH_SHORT).show();
        }
    }
    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
        }
    }
}

请问checkbox一直是空是为什么?

如果你的checkbox在fragment中,那你这个控件初始化就有问题,应该在fragment中,而不是activity。具体你可以参考下面这篇文章的第三节

我用#CSDN#这个app发现了有技术含量的博客,小伙伴们求同去《Android-面试题Fragment详解》, 一起来围观吧 https://blog.csdn.net/g984160547/article/details/117930956?utm_source=app&app_version=4.9.3&code=app_1562916241&uLinkId=usr1mkqgl919blen

如有帮助