뷰페이저 ( viewpager ) 를 WRAP_CONTENT 로 설정을 해도 match_parent 적용 되는 문제 해결
viewpager 아래에 layout을 둬야 하는데 무조건 match_parent 적용되는 viewpager 때문에
고생하시는 분들이라면 참고하세요 ^^
Custom viewpagr 만들어 사용하는 방법
public class HeightWrappingViewPager extends ViewPager { public HeightWrappingViewPager(Context context) { super(context); } public HeightWrappingViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST; if(wrapHeight) { /** * The first super.onMeasure call made the pager take up all the * available height. Since we really wanted to wrap it, we need * to remeasure it. Luckily, after that call the first child is * now available. So, we take the height from it. */ int width = getMeasuredWidth(), height = getMeasuredHeight(); // Use the previously measured width but simplify the calculations widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); /* If the pager actually has any children, take the first child's * height and call that our own */ if(getChildCount() > 0) { View firstChild = getChildAt(0); /* The child was previously measured with exactly the full height. * Allow it to wrap this time around. */ firstChild.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)); height = firstChild.getMeasuredHeight(); } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } }
viewpagr onPageChangeListener 사용하는 방법
@Override public Object instantiateItem(ViewGroup collection, int page) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = (View) inflater.inflate(R.layout.page_item , null); view.setTag(page);
private ViewPager pager; @Override protected void onCreate(Bundle savedInstanceState) { pager = findViewById(R.id.viewpager); pager.setOnPageChangeListener(new SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { resizePager(position); } }); public void resizePager(int position) { View view = pager.findViewWithTag(position); if (view == null) return; view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); //The layout params must match the parent of the ViewPager RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width height); pager.setLayoutParams(params); } }
'Android | JAVA' 카테고리의 다른 글
안드로이드 java Arraylist 역순 정렬 (0) | 2014.06.18 |
---|---|
안드로이드 Notification 상태바 알림 코드 (0) | 2014.06.18 |
안드로이드 페이스북 Intent 공유하기 (0) | 2014.06.13 |
안드로이드 킷캣 상태바 투명 처리 ios 처럼 (android kitkat status bar ) (2) | 2014.03.15 |
안드로이드 레이웃 가로 세로 사이즈 구하기 및 비율로 사이즈 변경 [ android layout size width , height] (0) | 2014.03.07 |