如何以编程方式设置ViewPager layoutParams?

cod*_*441 4 java android android-viewpager

我有以下代码,但我得到一个例外

java.lang.ClassCastException:android.support.v4.view.ViewPager $ LayoutParams无法强制转换为android.view.ViewGroup $ MarginLayoutParams

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.question_details_full_photo_view_pager);
        Bundle bundle = getIntent().getExtras();
        ArrayList<String> imageUrls = bundle.getStringArrayList("imageUrls");
        ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(this, imageUrls, true);

        android.support.v4.view.ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager_full_photo);


        android.support.v4.view.ViewPager.LayoutParams layoutParams = new LayoutParams();
        layoutParams.width = LayoutParams.MATCH_PARENT;
        layoutParams.height = LayoutParams.MATCH_PARENT;
        viewPager.setLayoutParams(layoutParams);


        viewPager.setAdapter(imagePagerAdapter);
    }
Run Code Online (Sandbox Code Playgroud)

d4v*_*idi 7

你真的不应该以编程方式设置布局参数只是为了将宽度和高度设置为"match_parent":这可以很容易地使用基本的xml声明来完成.

但是,如果您需要更高级的东西,您没有指定 - 例如调整边距或动态添加视图,请考虑使用与您的大小写匹配的布局包装ViewPager.例如:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager_full_photo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,要调整边距(例如):

ViewPager pager = (ViewPager) findViewById(R.id.view_pager_full_photo);
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) pager.getLayoutParams();
lp.topMargin += TOP_MARGIN_HEIGHT_PX;
Run Code Online (Sandbox Code Playgroud)

等等

请注意,在这种情况下,调用pager.getLayoutParams()返回布局参数是包装RelativeLayout布局参数 - 可以更容易地根据您的需要进行操作.