簡體   English   中英

如何以編程方式設置 ViewPager layoutParams?

[英]How can I set ViewPager layoutParams programmatically?

我有以下代碼,但出現異常

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);
}

您真的不應該僅僅為了將寬度和高度設置為“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>

在這種情況下,要調整邊距(例如):

ViewPager pager = (ViewPager) findViewById(R.id.view_pager_full_photo);
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) pager.getLayoutParams();
lp.topMargin += TOP_MARGIN_HEIGHT_PX;

等等。

請注意,在這種情況下,調用 pager.getLayoutParams() 返回布局參數是包裝的 RelativeLayout布局參數- 可以更輕松地操作以滿足您的需要。

這是因為您在此上下文中誤解了LayoutParams :設置 ViewPager 的布局參數會將其布局在其父級(即 ViewGroup)中。 因此,您必須傳遞ViewGroup.LayoutParams的實例。
如果您想在 ViewPager 中布置組件,則必須使用ViewPager.LayoutParams實例設置子組件的布局參數

val pager = findViewById(R.id.view_pager);

val params = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT); params.setMargins(44, 44, 44, 44); pager.layoutParams = params

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM