我有一个应用程序,用户可以使用单个活动中的开关在列表片段和地图片段之间进行切换。我在用户切换片段视图onCreateOptionsMenu时遇到问题。
这已经成为一个问题,因为我在操作栏中有一个微调器,它允许用户将数据过滤到选择的过滤器中,并且如果用户决定切换视图,它将被重置。
IE。在列表视图上通过“英语地震”进行过滤可显示所需的结果,但由于地图片段再次调用onCreateOptionsMenu,因此切换到地图视图会重置。
MainActivity中的onCreateOptionsMenu方法
//Inflating Menue
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.toolbar_menu,menu);
MenuItem item = menu.findItem(R.id.spinner);
spinner = (Spinner) item.getActionView();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.action_share, getResources().getStringArray(R.array.Planets)){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Explicitly used to turn spinner into an icon
LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.action_share, parent, false);
return view;
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setBackground(getResources().getDrawable(android.R.drawable.ic_menu_search));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString();
ChangeView(selectedItem);
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent)
{
}
});
return true;
MainActivity中onCreate中的片段切换代码
onOffSwitch = (Switch) findViewById(R.id.switchy);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
//Changes to the map Fragment
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.framlayoutMap, new NonListfragment());
ft.addToBackStack(null);
ft.commit();
}
else
{
//Changes to the list fragment
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.framlayoutMap, new EQListFragment ());
ft.addToBackStack(null);
ft.commit();
}
}
});
//Used to set it so the starting of the application does not have blank fragment
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.framlayoutMap, new EQListFragment ());
ft.commit();
onCreate在列表片段中
public class EQListFragment extends ListFragment implements AdapterView.OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(false);
}
地图片段中的onCreate没有将sethasOptionsMenu设置为false,因为它扩展了FragmentActivity
问题在于如何在加载活动时停止在父活动中调用onCreateOptionsMenu的片段。旋转设备时似乎也会发生这种情况。