簡體   English   中英

在片段中獲取 TabLayout 視圖返回 NullPointerException

[英]Getting TabLayout view in fragment returns NullPointerException

我正在嘗試將TabLayout添加到片段中,我通過多個教程討論了實現TabLayout的主題,它們大致相同。 我按照教程更改了一些方法以適應片段而不是通常的活動,但是在編譯后它返回一個錯誤,通過findViewById從 xml 文件獲取Tablayout 盡管我已經檢查過,但我還沒有設法找到做錯了什么。 TabLayout位於片段中,因為我將BottomNavigation用於應用程序的主導航,但我想使用TabLayout在片段內顯示額外信息。

這是包含 TabLayout 的片段

public class LocationsFragment extends Fragment {


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

    //The next line has the NullPointerException.
        TabLayout tabLayout = getView().findViewById(R.id.tabLayout);
        TabItem discoveredTab = getView().findViewById(R.id.discoveredTab);
        TabItem allLocationsTab = getView().findViewById(R.id.allTab);
        ViewPager viewPager = getView().findViewById(R.id.viewPager);

        PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(pagerAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                if (tab.getPosition() == 0){
                    pagerAdapter.notifyDataSetChanged();

                } else if (tab.getPosition() == 1){
                        pagerAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        View root = inflater.inflate(R.layout.fragment_locations, container, false);
        return root;
    }

這是尋呼機適配器 class

public class PagerAdapter extends FragmentPagerAdapter {


    private int numOfTabs;


    public  PagerAdapter(FragmentManager fragmentManager, int numOfTabs){
        super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.numOfTabs = numOfTabs;

    }
    @NonNull
    @Override
    public Fragment getItem(int position) {

        switch (position){
            case 0:
                return new TabDiscoveredFragment();
            case 1:
                return new TabAllFragment();
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return numOfTabs;
    }
}

這是布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout    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=".ui.journey.JourneyFragment">

    <RelativeLayout
        android:id="@+id/statLayout"
        android:layout_width="match_parent"
        android:layout_height="65sp"
        android:layout_marginStart="20sp"
        android:layout_marginEnd="20sp"
        android:layout_marginTop="30sp"
        android:background="@drawable/layout_bg_round_all">

//TextViews which are irrelevant to the example        

    </RelativeLayout>


        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/statLayout"
            android:layout_marginTop="20sp">

            <com.google.android.material.tabs.TabItem
                android:id="@+id/discoveredTab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Discovered" />

            <com.google.android.material.tabs.TabItem
                android:id="@+id/allTab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="All locations" />

        </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/viewPager">
    </androidx.viewpager.widget.ViewPager>
</RelativeLayout>

在此處輸入圖像描述

您不能在onCreateView()片段生命周期方法中使用getView() 。因為尚未創建片段視圖; 實際上onCreateView()創建了這個視圖並將其返回。

您只能在onCreateView()之后的片段生命周期方法中使用getView() )

要解決這個問題,您需要使用膨脹視圖本身,將其應用於您的代碼,將getView()替換為root ...但在方法的最開始聲明它。

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment_locations, container, false);
    
    //The next line has the NullPointerException.
    TabLayout tabLayout = root.findViewById(R.id.tabLayout);
    TabItem discoveredTab = root.findViewById(R.id.discoveredTab);
    TabItem allLocationsTab = root.findViewById(R.id.allTab);
    ViewPager viewPager = root.findViewById(R.id.viewPager);

    PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(pagerAdapter);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
            if (tab.getPosition() == 0){
                pagerAdapter.notifyDataSetChanged();

            } else if (tab.getPosition() == 1){
                    pagerAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    return root;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM