简体   繁体   English

为什么 findViewById() 返回“null”?

[英]Why does findViewById() returns “null”?

I have an important issue with java我对 java 有一个重要问题
I have this code:我有这个代码:

package fr.christian.lbcde;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;

import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import fr.christian.lbcde.ui.main.PageViewModel;
import fr.christian.lbcde.ui.main.SectionsPagerAdapter;

public class MainActivity extends AppCompatActivity {

    PageViewModel pageViewModel;
    View activity_main, tab_create, tab_connect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        FloatingActionButton fab = findViewById(R.id.fab);

        tab_connect = findViewById(R.id.tab_connect);
        tab_create = findViewById(R.id.tab_create);
        System.out.print("Result of tab_connect : ");
        System.out.print(findViewById(R.id.tab_connect));
        System.out.print(" ");
        System.out.println(tab_connect==null);
        System.out.print("Result of tab_create : ");
        System.out.print(findViewById(R.id.tab_create));
        System.out.print(" ");
        System.out.println(tab_create==null);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addNew();
            }
        });
//        hideAll();
//        tab_connect.setVisibility(View.VISIBLE);
        pageViewModel.addTabListener(new PageViewModel.tabChangeListener() {
            @Override
            public void onChangeTab(View view, int tab) {
                switch (tab) {
                    case 1:
                        hideAll();
                        tab_connect.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        hideAll();
                        tab_create.setVisibility(View.VISIBLE);
                        break;
                    default:
                        new Toast(getApplicationContext())
                                .makeText(getApplicationContext(), "Rien a afficher pour cet onglet", Toast.LENGTH_SHORT)
                                .show();
                }
            }
        });
    }

    public void addNew() {
        new Toast(getApplicationContext())
                .makeText(getApplicationContext(), "Cette option n'est pas encore disponible", Toast.LENGTH_SHORT)
                .show();
    }

    public void hideAll() {
        View[] views = {
                tab_create,
                tab_connect
        };
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.INVISIBLE);
        }
        ;
    }

}

and four files for my layouts:和我的布局的四个文件:

activity main.xml:活动 main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.LeBonCoinDeLÉvangile.AppBarOverlay">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            app:tabSelectedTextColor="?attr/colorPrimaryVariant"/>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:background="?attr/colorPrimary"
        app:srcCompat="@android:drawable/ic_menu_info_details" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>


fragment_main.xml fragment_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tab_create"
    android:orientation="vertical"
    android:layout_marginStart="@dimen/activity_horizontal_margin"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    android:layout_marginEnd="@dimen/activity_horizontal_margin"
    android:layout_marginBottom="@dimen/activity_vertical_margin"
    android:visibility="invisible">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TAB_CREATE"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BONJOUR LES ÉLËPHANTS"/>
</LinearLayout>

create_main.xml: create_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tab_connect"
    android:orientation="vertical"
    android:layout_marginStart="@dimen/activity_horizontal_margin"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    android:layout_marginEnd="@dimen/activity_horizontal_margin"
    android:layout_marginBottom="@dimen/activity_vertical_margin">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TAB_CONNECT"/>
    <TextView
        style="@style/h2textStyle"
        android:text="@string/titleConnect_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/loginConnect_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />
</LinearLayout>

and login_main.xml:和 login_main.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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/tab_connect" android:orientation="vertical" android:layout_marginStart="@dimen/activity_horizontal_margin" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_marginEnd="@dimen/activity_horizontal_margin" android:layout_marginBottom="@dimen/activity_vertical_margin"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TAB_CONNECT"/> <TextView style="@style/h2textStyle" android:text="@string/titleConnect_text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/loginConnect_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:text="Name" /> </LinearLayout>


The problem is that at the lines: 问题在于:
null


and

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TAB_CREATE"/>

I have this result (for the both):我有这个结果(对于两者):

 null

So I can't remove the error "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference" in hideAll() , tab_create.setVisibility(View.VISIBLE) , etc... because when I initialize my layouts, they are initialized with a null object (and not my layouts). So I can't remove the error "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference" in hideAll() , tab_create.setVisibility(View.VISIBLE)等...因为当我初始化我的布局时,它们被初始化为 null object (而不是我的布局)。
I add some lines like我添加了一些行,例如

 <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TAB_CREATE"/>

in my file to see if those tabs are really those I see on my screen and its appear that I really see them (when I cancel the lines with the layouts visibility).在我的文件中查看这些选项卡是否真的是我在屏幕上看到的那些选项卡,并且看起来我真的看到了它们(当我取消具有布局可见性的行时)。
Thanks for your help!谢谢你的帮助!

Your tab_connect etc. are include d in fragment_main layout and not in activity_main layout that is inflated when you call findViewById() for those ids.您的tab_connectincludefragment_main布局中,而不是在您为这些 ID 调用findViewById()时膨胀的activity_main布局中。 The code you posted does not show where you're using fragment_main but what is certain is that it is not in your activity's view hierarchy at the time when you try to look up those views.您发布的代码没有显示您在哪里使用fragment_main但可以肯定的是,当您尝试查找这些视图时,它不在您的活动的视图层次结构中。

Either move the findViewById() calls and whatever you're doing with the views to the fragment, or move the views from the fragment to your main activity.findViewById()调用以及您对视图所做的任何操作移至片段,或将视图从片段移至主要活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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