所以,我试图在Android应用程序的SettingsFragment中使用Switch,但似乎IDE不会在XML中看到它。我使用了调试器,看来root.findViewById(R.id.physicalEffortSwitch)返回null ..这只是没有任何意义..有人吗?这将是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="100dp">
<Switch
android:id="@+id/physicalEffortSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingHorizontal="30dp"
android:paddingVertical="17sp"
android:text="@string/show_jobs_that_require_physical_effort"
android:textSize="15sp"
android:checked="false"
android:textOff="@string/off"
android:textOn="@string/on"
/>
<Button
android:id="@+id/saveChangesButton"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:layout_marginTop="350dp"
android:layout_gravity="center_horizontal"
android:paddingVertical="20dp"
android:paddingHorizontal="15dp"
android:text="@string/save_changes"
android:background="#d3d3d3"
/>
</LinearLayout>
这是我的SettingsFragment代码:
public class SettingsFragment extends Fragment {
private View root;
private boolean physicalEffortPosts;
public static int range;
public static boolean physicalEffort;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_settings, container, false);
setup();
return root;
}
private void setup(){
Switch physicalEffortSwitch = (Switch) this.root.findViewById(R.id.physicalEffortSwitch);
physicalEffortSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
physicalEffort = physicalEffortSwitch.isChecked();
}
});
}
[检查您在Java文件中导入的Switch
类是否正确(例如,在xml中使用的同一类)。 Toolbar
通常会发生这种情况(至少有两个,并且如果您输入的是错误的一个,并且事情不能正确进行/不能强制转换并最终为null)。