Android ViewPager的初始化及遇到的切换异常,界面异常拉伸

Android ViewPager初始化(添加布局子界面,添加页面切换监听):

private ViewPager viewPager;
private View view1,view2,view3;

private void InitViewPager() {
    viewPager= (ViewPager) findViewById(R.id.V_Pager);
    views=new ArrayList<View>();
    LayoutInflater inflater=getLayoutInflater();
    view1=inflater.inflate(R.layout.layout1, null);       
    view2=inflater.inflate(R.layout.layout2, null);
    view3=inflater.inflate(R.layout.layout3, null);
    views.add(view1);
    views.add(view2);
    views.add(view3);
    viewPager.setAdapter(new MainActivity.MyViewPagerAdapter(views));
    viewPager.setCurrentItem(0);//设置初始显示界面Item(0),即R.layout.layout1
    viewPager.setOnPageChangeListener(new MainActivity.MyOnPageChangeListener());
    }

发现在切换ViewPager的子界面时,界面会异常拉升,最后发现是其中一个layout使用了以下这行代码导致的,将其去掉即可。

android:fitsSystemWindows="true"

另补上InitViewPager()中的MyViewPagerAdapter:

private class MyViewPagerAdapter extends PagerAdapter {
    private List<View> mListViews;
    public MyViewPagerAdapter(List<View> mListViews) {
        this.mListViews = mListViews;     }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object)
    {
        container.removeView(mListViews.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(mListViews.get(position), 0);
        return mListViews.get(position);
    }

    @Override
    public int getCount() {
        return  mListViews.size();    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0==arg1;
    }
}

页面切换监听及事件:

private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        public void onPageScrollStateChanged(int arg0) {
        }
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    showToast("page0");
                    break;
                case 1:
                    showToast("page1");
                    break;
                case 2:
                    showToast("page2");
                    break;
                default:                 
                    break;
            }
    }
}

showToast:

private void showToast(final String str) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();       }
    });
}

以上都是放在MainActivity.java里的

Android ViewPager的初始化及遇到的切换异常,界面异常拉伸_第1张图片

时间给空想者痛苦,给创造者幸福。---麦金西

你可能感兴趣的:(Android界面布局)