Android: "SetId in a For Loop using the index value"
Android: "SetId in a For Loop using the index value"
我正在尝试在 For 循环中创建一堆 ImageView。我想将视图设置在彼此下方。为此,我想将视图的 id 设置为 for 循环的 i 值,然后将 LayoutParam BELOW 设置为 i-1 的 id。
for (int i = 0; i < a.length(); i++)
{
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.board);
img.setId(i);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) img.getLayoutParams();
lp.addRule(RelativeLayout.BELOW, i-1);
img.setLayoutParams(lp);
}
当 i 不为 0 时,这会出现问题。然后我收到警告 "expected resource of type id",我在无数地方阅读过 View.generateViewId()
很容易解决,但是这会生成一个随机 ID,因此我可以' t 在下一个循环中到达前一个 id。
怎么能做到这一点?
however this generates a random id therefore i can't reach the previous id on the next loop.
将 id 值或整个 ImageView 对象存储在 Arraylist 中。
然后您可以查找以前的 ID 或只使用 generate 方法,然后在视图本身上使用 getId 方法。
或者忘掉它,使用垂直的LinearLayout
我正在尝试在 For 循环中创建一堆 ImageView。我想将视图设置在彼此下方。为此,我想将视图的 id 设置为 for 循环的 i 值,然后将 LayoutParam BELOW 设置为 i-1 的 id。
for (int i = 0; i < a.length(); i++)
{
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.board);
img.setId(i);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) img.getLayoutParams();
lp.addRule(RelativeLayout.BELOW, i-1);
img.setLayoutParams(lp);
}
当 i 不为 0 时,这会出现问题。然后我收到警告 "expected resource of type id",我在无数地方阅读过 View.generateViewId()
很容易解决,但是这会生成一个随机 ID,因此我可以' t 在下一个循环中到达前一个 id。
怎么能做到这一点?
however this generates a random id therefore i can't reach the previous id on the next loop.
将 id 值或整个 ImageView 对象存储在 Arraylist 中。
然后您可以查找以前的 ID 或只使用 generate 方法,然后在视图本身上使用 getId 方法。
或者忘掉它,使用垂直的LinearLayout