简体   繁体   English

Android 工作室 null object 更改组件可见性时出现参考错误

[英]Android studio null object reference error while changing component visibility

I'm making an app that displays the same menus for different users, each menu being a fragment, but depending on the user certain things are visible and others aren't.我正在制作一个应用程序,它为不同的用户显示相同的菜单,每个菜单都是一个片段,但根据用户的不同,某些东西是可见的,而另一些则不是。

However, when I try to set a component's visibility as GONE I get a null pointer exception error, I'm still testing so I'm only using a textView on the fragment xml.但是,当我尝试将组件的可见性设置为GONE时,出现 null 指针异常错误,我仍在测试,因此我仅在片段 xml 上使用 textView。

I've already tried initializing both the TextView and the FragmentMenuEncomenda , the class of the fragment I'm using, objects, both inside the if clause before the onCreate() method, and after the setContentView() , like the tabLayout and viewPager .我已经尝试初始化TextViewFragmentMenuEncomenda ,我正在使用的片段的 class 对象,都在onCreate()方法之前的 if 子句内和setContentView()之后,如tabLayoutviewPager

The if clause was only to make sure the user type was correct and the code in question is as follows: if 子句只是为了确保用户类型正确,有问题的代码如下:

public class PaginaInicialCliente extends AppCompatActivity {

    private SharedPreferences sharedpreferences;

    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        tabLayout = findViewById(R.id.tabLayoutCliente);
        viewPager = findViewById(R.id.viewPagerCliente);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        //fragments a adicionar
        adapter.addFragment(new FragmentMenuEncomendas(), "Encomendas");
        adapter.addFragment(new FragmentMenuOpcoes(), "Opções");

        //inicializar o tab layout
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);

        if (sharedpreferences.getInt("tipo",0)==3) {
            Log.d("USER_DEBUG","Cliente");
            FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
            
            //THE ERROR IS HERE
            fragmentMenuEncomendas.getActivity().findViewById(R.id.textViewEncomendas).setVisibility(View.GONE);
        }

    }
}

The FragmentMenuEncomenda class: FragmentMenuEncomenda class:

public class FragmentMenuEncomendas extends Fragment {

    View v;

    public FragmentMenuEncomendas(){
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.encomendas_fragment, container, false);
        return v;
    }
}

The xml file: xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textViewEncomendas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

All the answers I've searched didn't work, I don't know if it's because I'm trying to change the visibility inside the on create method.我搜索过的所有答案都没有用,我不知道是不是因为我试图改变 on create 方法中的可见性。

Because view is not created when you call the function.因为调用 function 时并没有创建视图。

public class FragmentMenuEmpresas extends Fragment {

    View v;
    View textView;
    boolean isTextViewShow = false;
    boolean isViewCreated = false;

    public FragmentMenuEmpresas() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.empresas_fragment, container, false);
        textView = v.findViewById(R.id.textViewEncomendas);
        return v;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (isTextViewShow) {

            textView.setVisibility(View.VISIBLE);
        } else {

            textView.setVisibility(View.GONE);
        }

        isViewCreated = true;
    }

    void setIsTextViewShow() {

        if (isViewCreated) {

            textView.setVisibility(View.VISIBLE);
        } else {

            isTextViewShow = true;
        }
    }

    void setIsTextViewGone() {
        
        if (isViewCreated) {

            textView.setVisibility(View.GONE);
        } else {

            isTextViewShow = false;
        }
    }
}

then you can call the setIsTextViewShow or setIsTextViewGone anytime you want然后您可以随时调用setIsTextViewShowsetIsTextViewGone

 FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
                       
 fragmentMenuEncomendas.setIsTextViewShow();//show
 fragmentMenuEncomendas.setIsTextViewGone();//gone

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

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