所以我在First-fragment中有一个名为changeText()的方法,当我从MainActivity调用它时,我在TextView上得到一个空指针异常。但是,如果我从Fragment类中的onCreate()调用它,它就可以工作。
任何帮助都会很棒。
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
int index = pager.getCurrentItem();
MyPagerAdapter adapter = ((MyPagerAdapter)pager.getAdapter());
FirstFragment fragment = (FirstFragment) adapter.getItem(index);
fragment.changeText("dssf");
public class FirstFragment extends Fragment {
TextView frv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
frv=(TextView) v.findViewById(R.id.tvFragFirst);
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
public void changeText(String text){
//frv=(TextView) getView().findViewById(R.id.tvFragFirst);
frv.setText(text);
}}
提前致谢。
编辑**
错误即将到来
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.//.slider.FirstFragment.changeText(FirstFragment.java:45)
at com.example.//.slider.MainActivity.onCreate(MainActivity.java:26)