以下是我的代码。 使用ViewPager我为两个页面及其类文件制作了2个XML文件。
现在我需要点击ViewPager的First Screen,新的活动应该启动。
我有2页,所以如果我点击第一个屏幕,A.class意图被调用。如果我点击第二个屏幕,应该调用B.class意图。
代码: -
MainActvity:
public class MainActivity extends ActionBarActivity {
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
/** set the adapter for ViewPager */
mViewPager.setAdapter(new SamplePagerAdapter(
getSupportFragmentManager()));
}
/** Defining a FragmentPagerAdapter class for controlling the fragments to
be shown when user swipes on the screen. */
public class SamplePagerAdapter extends FragmentPagerAdapter {
public SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
if (position == 0) {
return new SampleFragment();
} else
return new SampleFragmentTwo();
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
SampleFragment.java
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, null);
return rootView;
}
}
SampleFragmentTwo.java
public class SampleFragmentTwo extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container,
false);
return rootView;
}
}
CustomSwipeAdapter:
public class CustomSwipeAdapter extends PagerAdapter {
@Override
public int getCount() {
return 0;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}
答案 0 :(得分:0)
正如其中一条评论中所提到的,在你的片段类中,A和B将onClick监听器放在视图上并从那里启动意图,如下所示:
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, null);
rootView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// do something when the button is clicked
Intent activityA = new Intent(getActivity(),ActivityA.class);
startActivity(activityA);
}
return rootView;
}
}
类似于你的第二个片段。