textView中的getIdentifier()返回null

时间:2018-05-31 18:57:50

标签: java android textview android-cardview android-identifiers

我试图通过for获取不同的ID。我所拥有的是一张CardView,每张卡都有不同的ID,我想在点击时获取数据。

我做到了:

 public void setToggleEvent(final GridLayout mainGrid) {
    for ( int i = 0; i < mainGrid.getChildCount(); i++){

        count = i;

        final CardView cardView = (CardView)mainGrid.getChildAt(i);

        cardView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                if(cardView.getCardBackgroundColor().getDefaultColor() == -1) {

                    for (int f = 0; f < mainGrid.getChildCount(); f++){

                        if (f == count) {
                            int index = f;

                            String idFood = "food" + index;
                            int resID = getResources().getIdentifier(idFood, "id", getPackageName());

                            foodName =  findViewById(resID);
                            foodName.getText();
                        }

                    }

                    //canvi color de fons
                    cardView.setCardBackgroundColor(Color.parseColor("#FF6F00"));


                    foodData = foodName.toString();
                   selectedVegetables.add(foodData);


                } else {

                    cardView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    Toast.makeText(VegetablesActivity.this, "Food Selected", Toast.LENGTH_SHORT).show();
                }


            }

        });

    }
}

每张卡都有一个ID:food0,food1,food2 ....

正如您在代码中所看到的,我这样做是为了获取ID:

String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName =  findViewById(resID);
foodName.getText();

然后:

foodData = foodName.toString();
selectedVegetables.add(foodData);

但是,当我运行它时,foodName为空(java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference

并且在此行中出现错误

foodName.getText();

有什么想法吗?  抱歉我的英语不好,不是我的母语,希望大家都明白这一点。

1 个答案:

答案 0 :(得分:-1)

我很惊讶!这实际上不符合逻辑!

foodName =  findViewById(resID);

int resID不是这样的:&#34; R.id.exampleId&#34; id的类型。

resID 仅提供整数值。