简体   繁体   中英

Accessing widget from other layout with 'findViewById' returns null

I am trying to get the state of a Switch widget. To do this I create a new variable like so : Switch notifSwitch = findViewById(R.id.notif_switch) .

However that does not work because now notifSwitch is null and casting setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() gets me a java.lang.NullPointerException .

I suspect it has to do with the fact that the widget with the ' notif_switch ' id (the Switch that I am trying to get the value of) is not (directly) in activity_main.xml , which is the layout I am passing to setContentView at the beginning of my onCreate method because if I add setContentView(R.layout.line_notif); before the Switch declaration, the code works fine. The app only consists of what is in the line_notif.xml layout, which is only the Switch and a TextView , but at least I don't have any errors and I am able to get the state of the Switch widget.

I do not know how to access the widget from my MainActivity.java file and cannot find a way to do so. I tried looking at as many posts as possible before making my own. I am sorry if I missed one that answers my question but I just cannot find a way to solve this problem and would really appreciate the help.

Thank you.

MainActivity.java :

...
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private MainActivity activity;
    private boolean notificationsOn=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.activity = this;

        ...

        // HERE IS THE PROBLEM

        Switch notifSwitch = findViewById(R.id.notif_switch); // notifSwitch = null
        // Error on next line
        notifSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    notificationsOn = true;
                    Toast.makeText(getApplicationContext(), "Notifications enabled", Toast.LENGTH_SHORT).show();
                } else {
                    notificationsOn = false;
                    Toast.makeText(getApplicationContext(), "Notifications disabled", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
...

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/colorPrimary"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        android:background="@color/colorPrimary"/>

</android.support.v4.widget.DrawerLayout>

activity_main_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view"
    ...>

    ...

    <item
        android:id="@+id/nav_notifications"
        app:actionLayout="@layout/line_notif"
        android:enabled="true"
        tools:ignore="MenuTitle" />

    ...

</menu>

line_notif.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/line_notif"
    android:background="@android:color/transparent">

    ...

    <Switch
        android:id="@+id/notif_switch"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="end"
        android:theme="@style/SwitchTheme"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:paddingTop="15dp"/>

</RelativeLayout>

Full error :

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projectname/com.example.projectname.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference

I suspect it has to do with the fact that the widget with the ' notif_switch ' id (the Switch that I am trying to get the value of) is not (directly) in activity_main.xml , which is the layout I am passing to setContentView at the beginning of my onCreate method

You're right, that's the issue. I suggest you to read this post on how to create widgets. You'll learn that the components allowed in a widget are limited and so your interaction with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM