Java Android-查找ImageView,然后设置其可见性

Java Android-查找ImageView,然后设置其可见性,java,android,android-studio,Java,Android,Android Studio,我有一个网格的图像视图(10x10),它们是星星。我试着随机化一个坐标,然后让那颗星可见。我的主要活动的XML是: <TableRow android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:visibility="invisible"> <

我有一个网格的图像视图(10x10),它们是星星。我试着随机化一个坐标,然后让那颗星可见。我的主要活动的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" />
但是,当运行我的应用程序时,我得到了错误

Caused by: java.lang.NullPointerException
                  at com.example.localadmin.myapplication1.MainActivity.OnClick(MainActivity.java:73)
第73行是“target.setVisibility(View.VISIBLE);”


有人能帮忙吗?提前感谢

您可以在这样一个静态数组中跟踪视图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
然后你可以选择一个随机的星星,然后像这样设置它的可见性

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布局中的表行不可见。然后你的随机星星就会出现

我希望我不必初始化所有这些ID,但如果这是唯一的方法,那就好了-谢谢!