E
E
EnGold2022-04-03 13:15:55
Java
EnGold, 2022-04-03 13:15:55

Why does switchcompat(sw4) return null?

i tried to make settings using dialog but i can't set switchcompat(sw4) setChecked because it can't bind to switchcomapt from dialog

case R.id.setting:
                    load();
                    AlertDialog.Builder builder = new AlertDialog.Builder(GameScreen.this);
                    RelativeLayout setting_screen = (RelativeLayout) getLayoutInflater().inflate(R.layout.setting, null);
                    builder.setView(setting_screen);
                    dialog = builder.create();
                    sw4 = findViewById(R.id.music);
                    dialog.show();
                    break;

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="260dp"
    android:layout_height="390dp"
    android:background="@drawable/wall"
    android:padding="7dp">

    <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/music"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:checked="true"
        android:drawableStart="@drawable/musictxt"
        android:gravity="left"
        android:minHeight="48dp"
        android:onClick="onof"
        android:scaleType="fitCenter" />

</RelativeLayout>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
EnGold, 2022-04-03
@EnGold

in short, it is necessary to initialize the dialog in OnCreate and give the switch not just findViewById, but [layout].findViewById

builder = new AlertDialog.Builder(GameScreen.this);
        RelativeLayout setting_screen = (RelativeLayout) getLayoutInflater()
                .inflate(R.layout.setting, null);
        builder.setView(setting_screen);
        dialog = builder.create();
        sw4 = setting_screen.findViewById(R.id.music);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question