我想在我的活动的操作栏中使用微调器是onCreateOptionsMenu:我使用this tutorial来实现这种方法。我的问题是当活动是午餐时,onNavigationItemSelected方法触发,并且交换机/案例上的代码运行,我为位置0设置的活动打开。我应该怎么做才能防止在活动午餐时运行开关/案例?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
SpinnerAdapter mSpinnerAdapter;
if(Build.VERSION.SDK_INT <= 10)
{
mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_data,android.R.layout.simple_spinner_item);
}
else
{
mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_data,android.R.layout.simple_spinner_dropdown_item);
}
ActionBar.OnNavigationListener mOnNavigationListener = new ActionBar.OnNavigationListener()
{
@Override
public boolean onNavigationItemSelected(int position, long itemId)
{
switch (position)
{
case 0:
Intent searchIntent = new Intent(ActivitySearchBusiness.this, ActivityFindBusinessCity.class);
startActivity(searchIntent);
break;
case 2:
Intent dealsIntent = new Intent(ActivitySearchBusiness.this, ActivityDeals.class);
startActivity(dealsIntent);
break;
case 3:
Intent eventsIntent = new Intent(ActivitySearchBusiness.this, ActivityEvents.class);
startActivity(eventsIntent);
break;
}
return true;
}
};
actionBar.setListNavigationCallbacks(mSpinnerAdapter,
return super.onCreateOptionsMenu(menu);
}
答案 0 :(得分:6)
onCreateOptionsMenu(Menu)
:
.... ....
将其删除并将其放入活动的onCreate(Bundle)
方法。
修改强>
声明全局boolean
变量:
boolean initializing = true;
将以下代码放在onCreate(Bundle)
:
SpinnerAdapter mSpinnerAdapter;
if(Build.VERSION.SDK_INT <= 10)
{
mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_data,android.R.layout.simple_spinner_item);
}
else
{
mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_data,android.R.layout.simple_spinner_dropdown_item);
}
ActionBar.OnNavigationListener mOnNavigationListener = new ActionBar.OnNavigationListener()
{
@Override
public boolean onNavigationItemSelected(int position, long itemId)
{
if (initializing) {
initializing = false;
} else {
switch (position)
{
case 0:
Intent searchIntent = new Intent(ActivitySearchBusiness.this, ActivityFindBusinessCity.class);
startActivity(searchIntent);
break;
case 2:
Intent dealsIntent = new Intent(ActivitySearchBusiness.this, ActivityDeals.class);
startActivity(dealsIntent);
break;
case 3:
Intent eventsIntent = new Intent(ActivitySearchBusiness.this, ActivityEvents.class);
startActivity(eventsIntent);
break;
}
}
return true;
}
};
//actionBar.setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
getActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);