I am trying to create a switch that makes a TextView appear and disappear when the switch is toggled on/off. My app keeps crashing since adding the java reference objects for the textview and switch, throwing a null pointer exception. I feel like it's something simple, any help is appreciated :)
I've updated this post since moving the code to the appropriate java file for the XML where my button is located as per Mike's recommendation. Now I am getting "Cannot resolve symbol" errors. Do I have my code in the proper methods?
public class OutputsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//find audio switch and textview on outputs fragment
Switch splitAudioSwitch = (Switch)findViewById(R.id.splitSwitch);
TextView splitAlertText = (TextView)findViewById(R.id.splitText);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_outputs, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// do your variables initialisations here except Views!!!
}
//Code for audio splitting switch on outputs fragment
splitAudioSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
splitAlertText.setVisibility(splitAlertText.VISIBLE);
} else {
splitAlertText.setVisibility(splitAlertText.INVISIBLE);
}
}
});
}
fragment_outputs.XML
<Switch
android:id="@+id/splitSwitch"
android:layout_width="216dp"
android:layout_height="101dp"
android:layout_marginTop="124dp"
android:button="@drawable/baseline_router_black_24dp"
android:checked="false"
android:text="@string/SplitSwitch"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.541"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="225dp"
tools:layout_conversion_absoluteWidth="354dp" />
<TextView
android:id="@+id/splitText"
android:layout_width="110dp"
android:layout_height="51dp"
android:text="@string/splitAlertText"
android:textAlignment="center"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="normal"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.385"
tools:visibility="invisible" />