我在onOptionsItemSelected()中创建了一个EditText,并试图在onClick()中获取它的信息。这里是有问题的代码:错误问题:android.widget.LinearLayout无法转换为android.widget.EditText
onOptionItemSelected(MenuItem item){
...
EditText mealCalories = new EditText(context);
mealCalories.setId(MealCalId) //in this example it's just an integer 1.
...
}
onclick(View v){
EditText mealCaloriesInBox = (EditText)findViewById(mealCalId);
}
当我还没有从项目中选择一个项目(因此没有所谓的onOptionItemSelected();)当我点击按钮,它不会崩溃。然而,当我实际上创建了EditText,并且我点击了它的按钮时它崩溃,因为它试图创建实例,给我提到了上述错误。任何想法,为什么它可以做到这一点?
编辑
这里有更多的我的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
switch(item.getItemId()) {
case R.id.addMeal:
trackMealItems++;
mealCalId++;
mealFatId++;
mealCarbId++;
mealProteinId++;
//the base layout
LinearLayout root = (LinearLayout)findViewById(R.id.linearLayout1);
//make the layout that holds the meal item and add it to the base layout
LinearLayout mealItem = new LinearLayout(context);
mealItem.setId(trackMealItems);
mealItem.setOrientation(LinearLayout.VERTICAL);
mealItem.setLayoutParams(mealItemParams);
root.addView(mealItem);
//make the TextView that holds the name of the meal and add it to the mealItem layout
EditText mealName = new EditText(context);
mealName.setLayoutParams(mealNameParams);
mealItem.addView(mealName);
//make the TextViews that hold the information about the meal and stick them in a
//horizontal LinearLayout
LinearLayout mealStats = new LinearLayout(context);
mealStats.setOrientation(LinearLayout.HORIZONTAL);
mealStats.setLayoutParams(mealStatParams);
mealItem.addView(mealStats);
EditText mealCalories = new EditText(context);
mealCalories.setId(mealCalId);
mealCalories.setLayoutParams(mealStatParams);
mealStats.addView(mealCalories);
EditText mealFat = new EditText(context);
mealFat.setId(mealFatId);
mealFat.setLayoutParams(mealStatParams);
mealStats.addView(mealFat);
EditText mealCarbs = new EditText(context);
mealCarbs.setId(mealCarbId);
mealCarbs.setLayoutParams(mealStatParams);
mealStats.addView(mealCarbs);
EditText mealProtein = new EditText(context);
mealProtein.setId(mealProteinId);
mealProtein.setLayoutParams(mealStatParams);
mealStats.addView(mealProtein);
return true;
case R.id.removeMeal:
LinearLayout removeMe = (LinearLayout)findViewById(trackMealItems);
removeMe.setVisibility(View.GONE);
trackMealItems--;
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v){
EditText mealCaloriesInTextBox = (EditText)findViewById(mealCalId);
}
我认为在'onOptionItemSelected'中,创建了'mealCalories'后,你将它添加到已经在屏幕上的其他视图之一中? – 2011-12-29 22:34:08
是的。它位于水平方向的LinearLayout内。 – 2011-12-30 03:49:19
如果错误是LinearLayout不能转换为EditText,那么LinearLayout与EditText具有相同的ID? – 2011-12-30 07:34:09