这是我的代码
package com.saverx.rushabh.saverx;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
View view;
private static final String ARG_SECTION_NUMBER = "section_number";
ViewPager viewPager;
//TabLayout tabLayout;
TabLayout tabLayout;
LayoutInflater inflater;
ViewGroup container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.container=container;
this.inflater=inflater;
this.view= inflater.inflate(R.layout.activity_main, container, false);
viewPager=(ViewPager)view.findViewById(R.id.viewPager);
viewPager.setAdapter(new sliderAapter(getSupportFragmentManager()));
tabLayout=(TabLayout)view.findViewById(R.id.sliding_tab);
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
//return view;
}
private class sliderAapter extends FragmentPagerAdapter {
public sliderAapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
@Override
public Fragment getItem(int position) {
Log.e("adapter", ""+position);
// return new CalendarFragment();
NewLeadsFragment obj= new NewLeadsFragment();
/* Bundle bundle=new Bundle();
bundle.putInt("position",position);
obj.setArguments(bundle);
return obj;*/
return obj;
}
@Override
public int getCount() {
return 3;// 3 tabs
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Leads";
case 1:
return "Meetings";
case 2:
return "Service";
}
return null;
}
}
}
例外是
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean)' on a null object reference
at com.saverx.rushabh.saverx.MainActivity.onCreate(MainActivity.java:33)
当我使用片段实例活动
时,此代码工作正常我正在使用tablayout,以便我可以拖动注册并使用tablayout登录。
运行时错误是:
java.lang.RuntimeException:无法启动活动ComponentInfo {com.saverx.rushabh.saverx / com.saverx.rushabh.saverx.MainActivity}:java.lang.NullPointerException:尝试调用虚方法'android.view。在空对象引用上查看android.view.LayoutInflater.inflate(int,android.view.ViewGroup,boolean)'
我总结一下,错误可能是由于我没有插入this.view=view
但是它抛出同样的异常
答案 0 :(得分:1)
onCreate活动中没有容器和inflater。您可能已将片段onCreateView中的代码复制到activity onCreate。 检查这些行。 :
this.container=container;
this.inflater=inflater;
this.view= inflater.inflate(R.layout.activity_main, container, false);