私は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を作成してボタンをクリックすると、インスタンスを作成しようとするとクラッシュし、前述のエラーが表示されます。それがなぜそれを行うことができるのかについてのアイデアはありますか?
EDIT
は、ここに私のコードの多くはである:あなたがfindViewById
を呼び出すときに、あなたのEditTextを作成するときにMealCalId
とmealCalId
:
@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'を作成した後、それを既に画面上の他のビューの1つに追加していますか? –
うん。これは、水平方向のLinearLayoutの内側にあります。 –
LinearLayoutをEditTextにキャストできないというエラーがある場合、LinearLayoutはEditTextと同じIDを持ちますか? –