So, I am trying to use a Switch in my Android app's SettingsFragment but it seems the IDE just won't see it in the XML. I used the debugger and it seems root.findViewById(R.id.physicalEffortSwitch) returns null.. it just doesn't make any sense.. anyone please? This would be my 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>
And this is my SettingsFragment code:
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();
}
});
}
Check that the Switch
class you imported in your java file is the correct one (e.g. the same one you used in the xml). This often happens with Toolbar
(there are at least two, and if you import the wrong one and things don't work right/can't be cast and end up null).