我想知道是否有人可以帮助我解决这个问题。我有一个按钮设置,当它被点击时,它应该导航到另一个 viewpager 页面。但是每次单击时,应用程序都会崩溃,并在 fragmenttab2 类的 onClick 处返回错误。这是我的主要活动。
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
viewPager.setCurrentItem(1);
}
}
这是包含 onClick 的片段:
public class FragmentTab1 extends SherlockFragment {
ViewPager viewPager;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity activity = getActivity();
if (activity != null) {
addListenerOnButton();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmenttab1, container, false);
return view;
}
public void addListenerOnButton() {
Button nextfrag = (Button) getView().findViewById(R.id.btn_nextfrag);
nextfrag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((ViewPager) viewPager.findViewById(R.id.pager)).setCurrentItem(1);
}
});
}
}
日志:
E/AndroidRuntime java.lang.NullPointerException
E/AndroidRuntime com.test.seriessample.FragmentTab1$1.onClick(FragmentTab1.java:58)