gpt4 book ai didi

java - Android - 找到一个 ImageView 然后设置它的可见性

转载 作者:行者123 更新时间:2023-11-30 10:18:41 27 4
gpt4 key购买 nike

我有一个 ImageViews (10x10) 网格,它们是星星。我试图随机化一个坐标,然后让那颗星可见。我的 MainActivity 的 XML 是:

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:visibility="invisible">

<ImageView
android:id="@+id/star_a1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:visibility="invisible"
app:srcCompat="@android:drawable/btn_star_big_on" />

<ImageView
android:id="@+id/star_b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:visibility="invisible"
app:srcCompat="@android:drawable/btn_star_big_on" />

<ImageView
android:id="@+id/star_c1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:visibility="invisible"
app:srcCompat="@android:drawable/btn_star_big_on" />

等我已将可见性设置为不可见。为了找到 ID 然后更改可见性,我做了:

int starID = getResources().getIdentifier(coord, "id", getPackageName());
ImageView target = (ImageView)findViewById(starID);
target.setVisibility(View.VISIBLE);

但是,在运行我的应用程序时,出现错误

Caused by: java.lang.NullPointerException
at com.example.localadmin.myapplication1.MainActivity.OnClick(MainActivity.java:73)

第 73 行是“target.setVisibility(View.VISIBLE);”。

有人可以帮忙吗?提前致谢

最佳答案

您可以像这样在静态数组中跟踪您的 View ID

static int[] stars = {
R.id.star_a1, R.id.star_b1, R.id.star_c1,
R.id.star_a2, R.id.star_b2, R.id.star_c2 // as many ids as you need...
};

然后你可以选择一个随机的星星并像这样设置它的可见性

int index = new Random().nextInt(stars.length);         // choose a random array index
int id = stars[index]; // grab the element from the array
ImageView chosenStar = (ImageView) findViewById(id); // find the right view
chosenStar.setVisibility(View.VISIBLE); // make the chosen view visible

这当然可以用更少的代码行来完成,但我想让每个步骤都清楚。另一件事:我认为您不应该使 xml 布局中的表行不可见。然后你的随机星星应该会出现!

关于java - Android - 找到一个 ImageView 然后设置它的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49119231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com