内部循环使用时findViewWithTag给出空对象引用

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

在Android应用我有4个按钮用于我已经分别1,2,3和4中给出的标记,我想在用于循环改变每个按钮上的文字是否匹配(或不)一定值我的代码,“我”在对环从1到4,我当然把它转换成一个string..but当我运行的代码它给我空对象引用和应用程序崩溃,出现错误的应用程序调用时答.setText();或任何其他方法.. **我曾尝试发起一个对象,并发现它通过它的一个循环外标签和它没有任何问题的工作

for(int i=1;i<=4;i++){
           Button ans=(Button) view.findViewWithTag(String.valueOf(i));
            if(i==correct()){
                ans.setText(x+y+"");
            }else{
                int z=rand.nextInt(100)+rand.nextInt(100);
                if(z==x+y){
                    ans.setText(z+rand.nextInt(100));
                }
                else{
                    ans.setText(z);
                }
            }
        }

错误给出:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference
        at com.example.braintrainer.MainActivity.go(MainActivity.java:52)
java android
1个回答
0
投票

绑定你的布局和解析使用childCount而不是标签的意见。

假设这是一个线性布局你有(但你可以相应调整):

    LinearLayout layout = (LinearLayout) findViewById(R.id.name_of_your_layout);
    for (int i = 0; i < layout.getChildCount(); i++) {
            View v = layout.getChildAt(i);
            //add your checks here and set the text using v.setText("...");  
        }

注:在你的循环,你定义i作为整数,然后你检查是否i == correct()。您是否正确()方法返回的应该是等于我的整数?也许你有,你不在这里分享代码更多的问题。

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