应用使用findViewWithTag和getTag时崩溃 [英] App crashes on using findViewWithTag and getTag
问题描述
我是android新手开发人员.我在活动布局中声明了3x3 gridLayout,在其中放置了9个imageViews,它们的标签从0到8.下面是布局代码的片段:
I am a novice android developer. I have declared a 3x3 gridLayout in my activity layout, in which I have put 9 imageViews with tags from 0 to 8. A snippet of the layout code is posted below:
<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()
方法:
In my main method, in the method drop_in()
, I'm trying to check if user has called it or not, and if the system has called it, I'm trying to retrieve the ImageView by tags, by using a random number as tag.
Here is the drop_in()
method:
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中,它显示以下错误:
In the logcat, it shows the following error:
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)
如何使用标签检索视图?
How can I retrieve the views using tags?
推荐答案
使用此行
ImageView计数器=(ImageView)view.findViewById(R.id.counter_topLeft);
ImageView counter = (ImageView) view.findViewById(R.id.counter_topLeft);
myview =(View)group.findViewWithTag(String.valueOf(i));
myview=(View) group.findViewWithTag(String.valueOf(i));
这篇关于应用使用findViewWithTag和getTag时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!