【问题标题】:getIdentifier() from a textView returns null来自 textView 的 getIdentifier() 返回 null
【发布时间】:2018-05-31 18:57:50
【问题描述】:

我正在尝试使用 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();

有什么想法吗? 对不起,我的英语不好,这不是我的母语,希望大家能理解。

【问题讨论】:

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


    【解决方案1】:

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

    foodName =  findViewById(resID);
    

    int resID 不会为你提供这样的:“R.id.exampleId”类型的 id。

    resID只为您提供一个整数值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多