java - Android Studio:为什么addRule()在RelativeLayout.LayoutParams中不起作用?

标签 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>


我希望你能帮助我。

最佳答案

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

   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只是为了进行一些测试,并且图像显示在底部。您可以根据需要调整代码。

关于java - Android Studio:为什么addRule()在RelativeLayout.LayoutParams中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41894722/

相关文章:

java - 尝试通过cmd运行java代码时出现JNI错误

java - 如何在不迭代的情况下从 HashMap 中获取一个条目

Android - 定期服务的最佳实践

java - 如何在字符串数组中使用整数?

java - 使用Spring ReflectionUtils

Android - 从动态创建的微调器中获取所选项目

android - 异步任务中的上下文是什么

android - 找不到 aapt2-proto-7.0.0-beta04-7396180.jar

android - 在 Android Studio 2.0 中即时运行(如何关闭)

java - 新线程多次