我尝试将参数传递给View pager中的另一个选项卡。但是没有传递值。我在onTabSelected()
函数中编写了代码。但是,只发生了空值。请帮助我。关注我的代码。
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
Bundle bundle=new Bundle();
bundle.putString("name", "From Activity");
//set Fragmentclass Arguments
MoviesFragment fragobj=new MoviesFragment();
fragobj.setArguments(bundle);
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
public class MoviesFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext=getArguments().getString("name"); // ERROR in NULLPointerExecption
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
TextView text=(TextView) rootView.findViewById(R.id.text1);
text.setText("Movie");
return rootView;
}
}
我尝试使用此代码,但在NullPointerException
中发生strtext
错误
答案 0 :(得分:0)
您需要做类似的事情:
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
//set Fragmentclass Arguments
MoviesFragment preInitializedFragment = (MoviesFragment) getSupportFragmentManager().findFragmentByTag(MoviesFragment.class.getName());
if (preInitializedFragment == null) {
Bundle bundle=new Bundle();
bundle.putString("name", "From Activity");
MoviesFragment mFragment=new MoviesFragment();
mFragment.setArguments(bundle);
ft.add(android.R.id.content, mFragment, MoviesFragment.class.getName());
} else {
ft.attach(preInitializedFragment);
}
}