我正在尝试通过点击一个按钮来更改viewpager片段。我有5个片段,每个片段都有自己的xml文件(frag1.xml、frag2.xml等)。每个片段都有5个按钮,应该转到viewpager的其他页面。但问题是如何在FragmentPageAdapter中检查哪个按钮被点击以及如何到达那里?
我将展示我拥有的代码,然后我认为它应该很清楚。将其看作具有底部点的主屏幕,当您单击某个点时,将转到相应的屏幕。
FragmentPagerAdapter
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 6;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int arg0) {
switch(arg0){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
case 4:
return new Fragment5();
default:
return null;
}
}
/** Returns the number of pages */
@Override
public int getCount() {
return PAGE_COUNT;
}
}
Frag1.java
public class Frag1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_one, container, false);
OnClickListener changeFrag = new OnClickListener() {
@Override
public void onClick(View v) {
/*When I click this button in my fragment, I'd like it to go to fragment 3 for example*/
}
};
ImageButton btnT = (ImageButton) v.findViewById(R.id.frag3);
btnT.setOnClickListener(changeFrag);
return v;
}
}
MainActivity
这段代码声明了一个名为MainActivity的Java类,它继承自FragmentActivity。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
//pager.setPageTransformer(true, new ZoomOutPageTransformer());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
这种情况可能发生吗?有人能帮我指明正确的方向吗?