![](/img/trans.png)
[英]Android: ArrayIndexOutOfBounds Exception on addRule in LayoutParams
[英]Android Studio: Why wouldn't addRule() work from 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
進行一些測試,圖像顯示在底部。 您可以根據需要調整代碼。
我解決了我的問題。
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.card_height), (int) getResources().getDimension(R.dimen.card_width));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.