[英]How to switch to tab 2 by clicking a button in tab 1?
I have three tabs, a list on the fragment in tab 1, I want to sent the position of the item I click to fragment two in tab 2 and have the viewpager switch to tab2. 我有三个选项卡,在选项卡1的片段上有一个列表,我想发送要单击的项目的位置,以便在选项卡2的两个片段,并将viewpager切换到tab2。 I am using an interface to sent the position to the main activity which works fine, invoking a method in fragment two passing it the position is returning a null pointer exception and viewpager is not switching.
我正在使用一个接口将该位置发送到工作正常的主活动,在片段2中调用一个方法,并将其传递给该位置,该位置返回一个空指针异常,并且viewpager未切换。
The method in MainActivity MainActivity中的方法
@Override
public void respond(int i) {
Toast.makeText(MainActivity.this,"INSIDE MAINACTIVITY AND i = "+i,Toast.LENGTH_SHORT).show();
try {
Bundle args = new Bundle();
args.putInt("chapters",i);
PhpFragment f2 = new PhpFragment();
f2.setArguments(args);
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(1);
viewPager.setCurrentItem(1);
}catch (Exception ex){
Toast.makeText(MainActivity.this,"Error from MAIN = "+ ex.toString(),Toast.LENGTH_LONG).show();
}
}
My FragmentPagerAdapter 我的FragmentPagerAdapter
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new JavaFragment();
case 1:
return new PhpFragment();
case 2:
return new NetFragment();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
If i follow your question... Than you should look into it. 如果我遵循您的问题...比您应该调查一下。
fragments communication in view pager 在视图寻呼机中分割通信
Or another trick is .. 或另一招是..
You're using ViewPager and you can take advantage of it. 您正在使用ViewPager,并且可以利用它。 You can add a tag to a ViewPager like this:
您可以像这样将标签添加到ViewPager:
Activity: 活动:
pager.setTag("some text"); // pager is a ViewPager object
Then you can get this data via ViewGroup in a fragment like this: 然后,您可以通过ViewGroup在如下片段中获取此数据:
Fragment: 分段:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
String result = container.getTag().toString();
// do something with the result
return view;
You can also setTag() to the container in the fragment. 您还可以将setTag()设置为片段中的容器。
Another solution (not mentioned here so far) is sending data through SharedPreferences, but I would suggest using tags if possible. 另一个解决方案(到目前为止,这里没有提到)是通过SharedPreferences发送数据的,但是我建议尽可能使用标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.