我正在尝试使用for
. 我拥有的是一个 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
是 null ( java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
)
并且在出现错误的这一行中
foodName.getText();
任何想法?对不起我的英语不好,这不是我的母语,希望每个人都能理解。