在自定义视图中使用视图分页器

时间:2019-07-02 17:43:28

标签: android android-viewpager android-custom-view

我想在自定义视图上使用viewpager 但是当将viewpager添加到coustomview时 并且创建的pagerAdapter在视图分页器中不显示布局。 怎么解决??

/ **********************************************


*************************************************** /

自定义视图:

class Slider扩展了ViewGroup {

private ViewPager viewPager;



public Slider(Context context) {
    super(context);
    Init();
}

public Slider(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    Init();
}

public Slider(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    Init();
}


private void Init(){

    viewPager = new ViewPager(getContext());
    viewPager.setAdapter(new PagerAdapter());
    addView(viewPager);


}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int final_width = 0 , final_height = 0;


    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);

    int width_mode = MeasureSpec.getMode(widthMeasureSpec);
    int height_mode = MeasureSpec.getMode(heightMeasureSpec);


    if(width_mode == MeasureSpec.EXACTLY){
        final_width = width;
    }else if (width_mode == MeasureSpec.AT_MOST){
        final_width = 200;
    }else {
        final_width = 200;
    }


    if(height_mode == MeasureSpec.EXACTLY){
        final_height = height;
    }else if (height_mode == MeasureSpec.AT_MOST){
        final_height = 200;
    }else {
        final_height = 200;
    }


    setMeasuredDimension(final_width,final_height);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {


    viewPager.layout(l,t,r,b);

}

}

Pager适配器:

PagerAdapter类扩展了android.support.v4.view.PagerAdapter {

private int[] layout = {
        R.layout.slide,
        R.layout.slide,
        R.layout.slide
};

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
    View view = LayoutInflater.from(container.getContext()).inflate(layout[position], container, false);
    container.addView(view);
    return view;
}

@Override
public int getCount() {
    return 3;
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
    return view == o;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    View view = (View) object;
    container.removeView(view);
}

}

0 个答案:

没有答案