2017-07-14 17 views
0

我想補充一點,包含TabLayout查看片段的片段,但我不斷收到錯誤:如何添加Android中

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout.newTab()' on a null object reference 
                   at ca.rev.revcore.MainActivity.onCreate(MainActivity.java:76) 

這是我想補充的佈局:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/rev_tablayout" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:theme="@style/RevStyle_PlaceNewBagBttn"> 

    <android.support.design.widget.TabItem 
     android:id="@+id/tabItem" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Tab1" /> 

</android.support.design.widget.TabLayout> 

這是我正在嘗試添加:

TabLayout tabLayout = (TabLayout) findViewById(R.id.rev_tablayout); 

tabLayout.addTab(tabLayout.newTab().setText("Upload")); 
tabLayout.addTab(tabLayout.newTab().setText("Pics")); 
tabLayout.addTab(tabLayout.newTab().setText("Vids")); 
tabLayout.addTab(tabLayout.newTab().setText("Papers")); 

tabLayout.getTabAt(0).setIcon(R.drawable.ic_publish_black_24dp); 
tabLayout.getTabAt(1).setIcon(R.drawable.ic_menu_camera); 
tabLayout.getTabAt(2).setIcon(R.drawable.ic_videocam_black_24dp); 
tabLayout.getTabAt(3).setIcon(R.drawable.ic_airplay_black_24dp); 

什麼可能我會丟失?

Vielen dank im voraus。

+0

給你充分activity.java代碼 –

+0

添加完整的代碼包括Java和xml文件 –

回答

3

如果你正在使用片段,那麼。更改

TabLayout tabLayout = (TabLayout) findViewById(R.id.rev_tablayout); 

TabLayout tabLayout = (TabLayout) view.findViewById(R.id.rev_tablayout); 

view是將膨脹佈局文件和onCreateView()方法返回視圖的對象。

+0

感謝@Piyush的迴應,但是這裏的觀點是什麼?抱歉。我是一個完整的ANdroid新手。 –

+1

'View view = inflater.inflate(R.layout.fragment_layout,container,false);''在'onCreateView()'方法中擴充佈局並返回視圖。 – Piyush

+0

我真的不能感恩@Piyush。在這個這麼久了。謝謝。 –

0

製表符佈局是否在activity_main xml中使用了id rev_tablayout,或者它是否在片段的佈局中?請檢查您嘗試訪問Tablayout的位置。

1

如果你正在使用片段,那麼。在你的OnCreate鑑於這樣的控件綁定,你吹你的佈局

View rootView = inflater.inflate(R.layout.fragment_, container, false); 
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tablayout); 
1

Override onCreateView() method in Fragment, and inflate the Fragment layouts using LayoutInflater Class object and by pass­ing the ViewGroup argu­ment which is the activity in which the frag­ment will be embedded.

演示

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

    View rootView = inflater.inflate(R.layout.your_xml_name, container, false); 
    TabLayout tabLayout = (TabLayout)rootView.findViewById(R.id.rev_tablayout); 
    return rootView; 
}