我有两张照片。我使用ViewPager单独显示它们。我想知道哪些是在屏幕上显示的。你能帮我解决一下吗?例如,当我滚动屏幕时,第一个图像将显示并向Toast发送消息,例如"这是第一个图像",对第二个图像执行相同的操作。提前致谢。这是我的代码
public class ViewPagerExample extends FragmentActivity{
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 2;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
{
return new ImageFragment(R.drawable.image1);
}
case 1:
{
return new ImageFragment(R.drawable.image2);
}
default:
return null;
}
}
}
}
和ImageFragment类
public class ImageFragment extends Fragment {
private final int imageResourceId;
public ImageFragment(int imageResourceId) {
this.imageResourceId = imageResourceId;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
imageView.setImageResource(imageResourceId);
return view;
}
}
答案 0 :(得分:1)
尝试这样的事情
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int pager_position) {
// show toast here for images
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
答案 1 :(得分:1)
您可以使用这些代码行来扫描滑动图像
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
System.out.println("Positoin is the=="+position);
if(position==0)
{
///on the zero position you can get the image
}
else
{
///on the first position you can get the image
}
}
};
答案 2 :(得分:1)
有一个方法yourViewpagerObject.getCurrentItem()
,它返回视图寻呼机当前已查看页面的位置