gpt4 book ai didi

Android - 在运行时更改 ViewPager 的高度

转载 作者:太空狗 更新时间:2023-10-29 12:41:08 25 4
gpt4 key购买 nike

我想更改 ViewPager 的高度,因为它包含一些具有不同高度的 child 。我读过 wrap_content 对于 ViewPager 是不可能的,所以我想在运行时更改它的高度。我已经试过了,但它不起作用:

pager.getLayoutParams().height=1000;

有人可以提供帮助吗?

CustomViewPager.class

public class CustomViewPager extends ViewPager {

/**
* Constructor
*
* @param context
* the context
*/
public CustomViewPager(Context context) {
super(context);
}

/**
* Constructor
*
* @param context
* the context
* @param attrs
* the attribute set
*/
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}

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

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

int height = 0;
for (int i = 0; i < getChildCount(); i++) {

View child = getChildAt(i);

child.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

int h = child.getMeasuredHeight();

if (h > height)
height = h;

}

heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
MeasureSpec.EXACTLY);

super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

}

xml文件:

<com.arsoft.ex.viewpager.CustomViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.arsoft.ex.viewpager.CustomViewPager>

主类:

tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (CustomViewPager) findViewById(R.id.viewPager);
adapter = new MyPagerAdapter(getSupportFragmentManager());

pager.setAdapter(adapter);

final int pageMargin = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);

tabs.setViewPager(pager);

FragmentPagerAdapter:

    public class MyPagerAdapter extends FragmentPagerAdapter {

private final String[] TITLES = { "Cook", "Recipe", "Comments" };

public MyPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}

@Override
public int getCount() {
return TITLES.length;
}

@Override
public Fragment getItem(int position) {
switch (position) {
case 0: **pager.getLayoutParams().height=100;**
return CookCardFragment.newInstance(position, pager);

case 1: **pager.getLayoutParams().height=400;**
return RecipeCardFragment.newInstance(position, pager);

case 2: **pager.getLayoutParams().height=1000;**
return CookCardFragment.newInstance(position, pager);
}
return null;
}

}

最佳答案

我以前见过这个问题。也许你可以像这样使用函数:

 ViewPager vp = (CustomViewPager) findViewById(R.id.viewPager);
...
ViewGroup.LayoutParams params = vp.getLayoutParams();
params.height = 1000;
vp.setLayoutParams(params);

关于Android - 在运行时更改 ViewPager 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25577385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com