Android Studio:为什么addRule()不能从RelativeLayout.LayoutParams中运行?

时间:2017-01-27 13:08:55

标签: java android android-studio relativelayout layoutparams

我会在RelativeLayout的左侧有一个ImageView。但是使用这个Java代码它不起作用。 ImageView位于RelativeLayout的中间位置。

RelativeLayout layout_hand = (RelativeLayout) main.findViewById(R.id.hand);
ImageView view = new ImageView(main);
view.setImageResource(R.mipmap.test_pokemon_cardback);
view.setContentDescription("field");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(R.dimen.card_height, R.dimen.card_width);
params.addRule(RelativeLayout.ALIGN_PARENT_START, RelativeLayout.TRUE);
view.setLayoutParams(params);
layout_hand.addView(view);

当我用xml测试它时,效果很好。但我会动态添加这个视图。

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/hand"
    android:layout_below="@+id/layout_deck"
    android:layout_toStartOf="@+id/layout_graveyard"
    android:layout_toEndOf="@+id/layout_resource_deck">

    <ImageView
        android:layout_width="@dimen/card_width"
        android:layout_height="@dimen/card_height"
        app:srcCompat="@mipmap/test_pokemon_cardback"
        android:contentDescription="@string/field"
        android:id="@+id/test"
        android:layout_alignParentStart="true" />
</RelativeLayout>

我希望你能帮助我。

2 个答案:

答案 0 :(得分:0)

我认为这可能会有所帮助:

   RelativeLayout layout_hand = (RelativeLayout)findViewById(R.id.hand);
    RelativeLayout.LayoutParams params = new  RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    ImageView view = new ImageView(this);
    view.setImageResource(R.mipmap.ic_launcher);
    view.setContentDescription("field");
    layout_hand.addView(view, params);
    RelativeLayout.LayoutParams lrp = (RelativeLayout.LayoutParams)view.getLayoutParams();
    lrp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    view.setLayoutParams(lrp);

注意我只使用RelativeLayout.ALIGN_PARENT_BOTTOM进行测试,图像显示在底部。您可以根据需要调整代码。

答案 1 :(得分:0)

我解决了我的问题。

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.card_height), (int) getResources().getDimension(R.dimen.card_width));
相关问题