应用程序在使用 findViewWithTag 和 getTag 时崩溃

App crashes on using findViewWithTag and getTag

我是新手 android 开发人员。 我在我的 activity 布局中声明了一个 3x3 gridLayout,我在其中放置了 9 个 imageViews,标签从 0 到 8。 下面发布了布局代码片段:

<GridLayout
        android:id="@+id/gridLayout"
        android:background="@drawable/board"
        android:columnCount="3"
        android:rowCount="3">

        <ImageView
            android:id="@+id/counter_topLeft"
            android:onClick="drop_in"
            android:tag="0"
            android:layout_column="0"
            android:layout_row="0" />

在我的主要方法中,在方法 drop_in() 中,我试图检查用户是否调用了它,如果系统调用了它,我试图通过以下方式检索 ImageView标签,通过使用随机数作为标签。 这是 drop_in() 方法:

public void drop_in(View view) // method invoked on tapping any grid cell
    {
        int i;
        ImageView counter = (ImageView) view;
        i = Integer.parseInt(counter.getTag().toString()); // getting the associated tags or basically cell number
        if(isHuman)
        { // do some stuff and then 
            isHuman=false;
        }
        //  now app will perform actions and wait for user input to do stuff again
        if(!isHuman)
        {
            Random random=new Random();
            i=random.nextInt(9);

            Object o=i;
            ViewGroup group = (ViewGroup) findViewById(R.id.gridLayout)
            myview=(View) group.findViewWithTag(o);
            Log.i("Info","View tag is "+myview.getTag().toString());
            isHuman=true;
         }
    }

在logcat中,显示如下错误:

2020-05-15 12:26:40.605 10000-10000/com.s090.tttsingleplayer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.s090.tttsingleplayer, PID: 10000
    java.lang.IllegalStateException: Could not execute method for android:onClick
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.view.View.getTag()' on a null object reference
        at com.s090.tttsingleplayer.MainActivity.drop_in(MainActivity.java:133)

如何使用标签检索视图?

也可以使用这条线

ImageView 计数器 = (ImageView) view.findViewById(R.id.counter_topLeft);

myview=(视图)group.findViewWithTag(String.valueOf(i));

这是我从 Official Android developer site :

复制的一句话

Tags

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

因此您不能在运行时使用标签来查找它们。我的建议是使用 int 数组来存储您的 ImageView 的 ID,并使用 Random class 生成随机索引:

int[] imageviewIds={R.id.image1,R.id.image2 \* .etc*\};
Random random=new Random();
i=random.nextInt(9);
myview=(View) group.findViewById(imageIds[i]);