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

标签 java android android-studio

我有一个 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/

相关文章:

android - 看不到作为依赖项添加的包内的类

java - 为什么我的应用程序每次运行时都会崩溃?没有错误

java - Web 应用程序中的随机 NoClassDefFound 错误

java - 读取字符行并获取文件位置

java - InvalidKeySpecException : How do I extract a private key from a . 文件?

android - ListView Item阴影+自定义选择器

java - 在非 Android Java 项目中使用 Android 应用程序的一部分

java - 为什么我的 ByteToMessageDecoder 解码方法从未被调用?

android - 如何从 EditText 获取字符?

java - 在 Java 中声明并初始化对象 - Android Studio