我有一个活动扩展到FragmentActivity,它有4个片段。我现在想要在按钮点击时打开fragment2,它存在于fragment1中。 简而言之,我想在按钮点击时从fragment1切换到片段2。 我的代码是: 公共类SampleActivity扩展了FragmentActivity {
static ViewPager mViewPager;
PagingAdapter TabAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new PagingAdapter(getSupportFragmentManager(), this);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(TabAdapter);
}
public class PagingAdapter extends FragmentPagerAdapter {
private Context context;
public PagingAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public Fragment getItem(int i) {
switch(i){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getString(R.string.page_tab_1);
case 1:
return context.getString(R.string.page_tab_2);
case 2:
return context.getString(R.string.page_tab_3);
case 3:
return context.getString(R.string.page_tab_4);
}
return "Fragment " + (position + 1);
}
}
public class Fragment1 extends Fragment{
Button btn_close = (Button) mydeals.findViewById(R.id.btn_close);
btn_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Needs to open fragment2 here.
});
}
我尝试使用id进行转换,但是下面的代码
打开了fragment4ViewPager viewpager = DealsActivity.mViewPager;
viewpager.setCurrentItem(getId());
答案 0 :(得分:0)
在Fragment1
版面中,在android:onClick="buttonClickMethod"
定义中添加属性Button
。然后在您的活动中,添加以下方法:
public void buttonClickMethod(View v) {
// some code to execute after button click
// ....
// You can open fragment 2 here, like this :
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.LAYOUT_ID_FOR_FRAGMENT2, FRAGMENT2);
ft.commit();
}
请注意,该方法的名称与android:onClick
属性中定义的名称相同。