在获取一个view.getTag空指针 [英] Getting a Nullpointer at view.getTag

查看:714
本文介绍了在获取一个view.getTag空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试设置标签和我的一个按钮的ID:

I try to set the Tag with the ID of one of my buttons:

     int boeserzufall = (int) (Math.random()*23);
     Button boese = arr.get(boeserzufall);
     boese.setBackgroundResource(R.drawable.williboese);
     boese.setTag(R.drawable.williboese);

这工作正常, boese.getTag()给我带来了正确的ID。 改编的ArrayList<按钮方式> 包含我的所有按钮

That works fine, boese.getTag() brings me the correct id. arr is an ArrayList<Button> that contains all my buttons.

现在在我的OnClick()方法,我想检查当前按钮具有相同渣油为 boese

Now in my OnClick() method I want to check if the current button has the same resId as boese

    b5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            count++;
            int resId = (Integer) arg0.getTag();
            if(resId == R.drawable.williboese) {
                Toast.makeText(MainActivity.this, "heeeee", Toast.LENGTH_SHORT).show();
            }

        }
    });

我的问题是,我得到当我尝试读取空指针异常 arg0.getTag()

编辑:

首先,我采取随机按钮我的数组并为此我想设置与 R.drawable.williboese 背景图像。
所以在我的25键我有比其他人不同的背景图片。这一次我一定要找到并比别人的反应不同...

First, I take a random button out of my array and therefor I want to set the background image with R.drawable.williboese. So on one of my 25 buttons I have a different background image than on the others. This one I have to find and react different than on the others...

推荐答案

据上次编辑,可以设置一个标记只在一个特定的按钮,出25这是autoboxed成一个整数一个int。你甚至都不需要标记的值,因为这是为非空只在特定的按钮。这应该做的:

According to your last edit, you set a tag only on one specific button, out of 25. This is an int autoboxed into an Integer. You do not even need the value of the tag, because this is non-null only on that specific button. This should do:

public void onClick(View arg0) {
    count++;
    if(view.getTag() != null) {
        Toast.makeText(MainActivity.this, "heeeee", Toast.LENGTH_SHORT).show();
    }
}

这篇关于在获取一个view.getTag空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆