为自定义视图设置布局参数

Set Layout Params for custom View

在 XML 中,我创建了一个 SwipeDeck (customView) 的新实体,如下所示:

<com.daprlabs.aaron.swipedeck.SwipeDeck
 android:id="@+id/swipe_deck"
 android:layout_width="match_parent"
 android:layout_height="20dp"
 swipedeck:card_spacing="15dp"
 swipedeck:max_visible="1"
 swipedeck:render_above="true"
 swipedeck:swipe_enabled="true">

现在我正在尝试以编程方式设置 x 和 y 位置。这很好用:

cardStack = (SwipeDeck) findViewById(R.id.swipe_deck);

    cardStack.setX(20);
    cardStack.setY(10+actionBarHeight);

当我尝试动态设置高度和宽度时,没有任何反应:

cardStack = (SwipeDeck) findViewById(R.id.swipe_deck);
    ViewGroup.LayoutParams params = cardStack.getLayoutParams();
    params.height=500;
    params.width =  screen_width - 40;
    cardStack.setLayoutParams(params);

一切都发生在 onCreate 中。有什么想法吗?

您应该针对包含它的 ViewGroup 声明 "params" 的类型。
例如,替换行

ViewGroup.LayoutParams params = cardStack.getLayoutParams();  

LinearLayout.LayoutParams params = cardStack.getLayoutParams();  

如果您的自定义视图在 LinearLayout 中