Android LinearLayout findViewById gets null



我这里有一个问题。我需要更改导航视图中的布局背景。这是我的工作

protected void onCreate(Bundle savedInstanceState) {
    try {
        ConnectivityManager con = (ConnectivityManager) getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo net = con.getActiveNetworkInfo();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        themeInfo = getSharedPreferences("THEMECONFIG",0);
        themeSetting = themeInfo.getString("theme","Základná");

        if (net != null && net.isConnected()) {
            if (isOnline()) {
                //setContentView(R.id.nav_header_logo);
                navHeaderLogo = (LinearLayout)findViewById(R.id.nav_header_logo);
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
                drawer.setDrawerListener(toggle);
                toggle.syncState();

                navigationView.setNavigationItemSelectedListener(this);

            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Hups, niečo je zle :(")
                        .setMessage("Internet nie je dostupný")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Hups, niečo je zle :(")
                    .setMessage("Chýba pripojenie k internetu. Zapnite prosím dáta alebo Wi-Fi a spustite aplikáciu znova.")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }

    } catch (Exception e) {
        Log.e("chyba", e.getMessage());
    }
    swt = (SwitchCompat)findViewById(R.id.lokalizationSwitch);
    if(ContextCompat.checkSelfPermission(Settings_activity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED)
    {
        swt.setChecked(false);
        checker = false;
    }
    else
    {
        swt.setChecked(true);
        checker = true;
    }
    swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            MainActivity.checker = false;
            MainActivity2.checker2 = false;
            MainActivity3.checker3 = false;

            if(isChecked == true)
            {
                if (ContextCompat.checkSelfPermission(Settings_activity.this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Settings_activity.this,
                            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                            permissionCheck);
                    checker = true;

                    }
            }
            else if (isChecked == false && checker == true)
            {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
                checker = false;
            }
        }
    });
    this.isCreated = true;
    themes = (Spinner) findViewById(R.id.comboBoxTheme);
    themeSetting = themeInfo.getString("theme","Základná");
    if(themeSetting.equals("Základná"))
    {
        themes.setSelection(0);
        setTheme(R.style.AppTheme);
        checker2 = false;
    }
    if(themeSetting.equals("Matrix"))
    {
        themes.setSelection(1);
        setTheme(R.style.AppThemeMatrixDivider);
        checker2 = false;
    }
    if(themeSetting.equals("Gamers"))
    {
        themes.setSelection(2);
        setTheme(R.style.AppThemeGamersDivider);
        checker2 = false;
    }
    themes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            int index = arg0.getSelectedItemPosition();
            if(!themeSetting.equals(themes.getItemAtPosition(index).toString()))
            {
                changeTheme(themes.getItemAtPosition(index).toString());
                checker2 = false;
            }

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            checker2 = true;
        }
    });
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    Button sett = (Button)findViewById(R.id.button_settings);
    TextView text = (TextView)findViewById(R.id.textview);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("setItemIconTintList",R.drawable.menu_text_color_normal) ));
    navigationView.setItemTextColor(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("setItemTextColor",R.drawable.menu_text_color_normal) ));
    navigationView.setBackgroundDrawable(ContextCompat.getDrawable(Settings_activity.this, themeInfo.getInt("setBackgroundDrawable",R.drawable.border_top_bottom_normal) ));
    sett.setTextColor(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("settSetTextColor",R.color.colorWhite) ));
    text.setTextColor(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("textSetTextColor",R.color.colorDefault) ));
    toolbar.setBackground(ContextCompat.getDrawable(Settings_activity.this, themeInfo.getInt("toolbarSetBackground",R.color.colorPrimary) ));
    toolbar.getNavigationIcon().setColorFilter(getResources().getColor(themeInfo.getInt("toolbarGetNavigationIcon()",R.color.colorWhite)), PorterDuff.Mode.SRC_ATOP);

}

当我使用LinearLayout navHeaderLogo=(LinearLayout)this.findViewById(R.id.nav_header_logo);时,它只会向我显示这样的错误

    E/chyba: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.lodka.lodkanadejeapp, PID: 12231
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lodka.lodkanadejeapp/com.example.lodka.lodkanadejeapp.Settings_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:156)
                      at android.app.ActivityThread.main(ActivityThread.java:6531)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
                      at com.example.lodka.lodkanadejeapp.Settings_activity.onCreate(Settings_activity.java:259)
                      at android.app.Activity.performCreate(Activity.java:6910)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864) 
                      at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
                      at android.os.Handler.dispatchMessage(Handler.java:105) 
                      at android.os.Looper.loop(Looper.java:156) 
                      at android.app.ActivityThread.main(ActivityThread.java:6531) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)

 

我知道这是不合时宜的,因为背景更改应该在其他地方进行。但是你们对我有什么解决方案吗?因为我几乎尝试了所有方法,但没有真正起作用。

这是我正在使用的 XML

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_header"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/border_top_bottom_normal"
    android:gravity="bottom"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:weightSum="1">

    <LinearLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/nav_header_logo"
        android:layout_width="match_parent"
        android:layout_height="@dimen/nav_header_height"
        android:background="@drawable/border_top_bottom_normal_logo"
        android:gravity="bottom"
        android:orientation="vertical"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:weightSum="1">
    <ImageView
        android:id="@+id/logoImg"
        android:background="@android:color/transparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="25pt"
        android:src="@mipmap/lodkauvodbp"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:srcCompat="@android:drawable/sym_def_app_icon"/>

    </LinearLayout>
</LinearLayout>

这是activity_settings.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"
    tools:openDrawer="start">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:weightSum="1"
        android:divider="?android:dividerHorizontal"
        android:showDividers="middle"
        android:orientation="vertical">
        <TextView
            android:id="@+id/textview1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="50px"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Nastavenia"
            android:textSize="25dp"
            android:typeface="serif" />
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="left">
                <TextView
                    android:id="@+id/labelswitch"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Povolenie pre lokalizáciu"
                    android:textSize="15dp"
                    android:typeface="serif"
                    android:gravity="left"
                    android:textColor="#000000"/>
                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="right">
                    <android.support.v7.widget.SwitchCompat
                        android:id="@+id/lokalizationSwitch"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:checked="true" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="left">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Výber farebnej témy"
                    android:textSize="15dp"
                    android:typeface="serif"
                    android:textColor="#000000"/>
                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="right">
                    <Spinner
                        android:id="@+id/comboBoxTheme"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textAlignment="textEnd"
                        android:layout_gravity="end"
                        android:drawSelectorOnTop="true"
                        android:entries="@array/theme_array" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        app:itemTextColor="@drawable/menu_text_color_normal"
        app:itemIconTint="@drawable/menu_text_color_normal"
        android:background="@drawable/border_top_bottom_normal">

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

    </android.support.design.widget.NavigationView>
</android.supp

ort.v4.widget.DrawerLayout>

PS:我知道这样的问题在这里已经解决了,但这对我来说是特定的问题

更新

:我更新了创建方法更新 2:更新了错误消息更新 3:新增activity_settings.xml

移动您的:

 setContentView(R.layout.activity_settings);

在超级调用之后,如下所示:

 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_settings);

如果你不在线(isOnline()是错误的(,你的视图永远不会被夸大,当你试图通过id查找内容时,这将导致问题。

好的,

我找到了一个解决方案。我只需要做这样的事情

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    View header = navigationView.getHeaderView(0);
    LinearLayout linear = (LinearLayout) header.findViewById(R.id.nav_header_logo);
    linear.setBackground(ContextCompat.getDrawable(this, R.drawable.border_top_bottom_matrix_logo));

这非常有效,nav_header_logo不再为空

最新更新