我试图通过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();
有什么想法吗? 抱歉我的英语不好,不是我的母语,希望大家都明白这一点。
答案 0 :(得分:-1)
我很惊讶!这实际上不符合逻辑!
foodName = findViewById(resID);
int resID
不是这样的:&#34; R.id.exampleId&#34; id的类型。
resID 仅提供整数值。