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

问题描述 投票:2回答:1

我有一个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);”。

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

java android android-studio
1个回答
1
投票

您可以在这样的静态数组中跟踪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布局中的表行不可见。然后你的随机明星应该出现!

© www.soinside.com 2019 - 2024. All rights reserved.