我的app遇到了问题。
我设置了一个带有三个操作栏标签的ViewPager
。
当应用程序打开时,下一个选项卡被预加载(或其他)
示例:我从标签A滑动到标签B.当显示标签B时,在后台创建标签C.
选项卡C本身有一个特殊的ActionBar菜单项,该选项应仅显示在选项卡3中。由于它已预加载,因此该符号将显示在选项卡B和选项卡C中。
如果我在标签B中拨打setHasOptionsMenu(false)
,标签C会用setHasOptionsMenu(true)
覆盖它(我仍然想显示特殊项目)
我用谷歌搜索并堆叠了几个小时来找到解决方法,但不幸的是,我没有得到任何结果。
有没有办法解决这个问题,有人可以向我解释这种行为吗?
编辑:某些代码。
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_pager);
mPagerAdapter =new MyPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
//invalidateOptionsMenu();
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabListener = new FilmKisteTabListener();
for (int tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(tabListener));
}
}
protected class FilmKisteTabListener implements ActionBar.TabListener {
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// Nothing
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
/*@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kiste_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this.getApplicationContext(), "YOU SHALL NOT PASS!!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}*/
@Override
public void libraryRefresh() {
/**
* Tell adapter to update the views
* content has changed
*/
mPagerAdapter.notifyDataSetChanged();
Toast.makeText(this, "Aktualisiert", Toast.LENGTH_SHORT).show();
}
@Override
public void onFilmAdded() {
/**
* Tell adapter to update the views
* content has changed
*/
mPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(0);
Toast.makeText(this, "Arbeit ist vollbracht", Toast.LENGTH_LONG).show();
}
@Override
public void onFilmDeleted(String name) {
mPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(0);
Toast.makeText(this, name + " wurde verbannt.", Toast.LENGTH_LONG).show();
}
@Override
public void onReturn() {
mViewPager.setCurrentItem(0);
}
@Override
public void onResume() {
super.onResume();
getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
片段1:LibraryFragment(默认加载)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_bibliothek, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
//View init here!
listView = (ListView) view.findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(this);
}
private void initialize() {
db = new DatabaseHelper(this.getActivity().getApplicationContext());
valueList = new ArrayList<Film>();
resList = new ArrayList<String>();
valueList = db.getAllFilms();
for(int i = 0; i < valueList.size(); i++) {
resList.add(valueList.get(i).getName());
}
adapter = new ArrayAdapter<String>(
this.getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, resList);
ad = new AlertDialog.Builder(this.getActivity())
.setTitle("Löschen?")
.setMessage("Der Film sollte nur gelöscht werden, wenn es keinen weiteren Teil gibt.")
.setPositiveButton("Ja", this)
.setNegativeButton("Nein", null);
}
public interface LibraryRefreshCallback {
public void libraryRefresh();
}
private void refresh() {
//TODO UPDATE
callback.libraryRefresh();
// Toast.makeText(this.getActivity(), "Aktualisiert", Toast.LENGTH_SHORT).show();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks
try{
callback = (LibraryRefreshCallback) activity;
}catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement LibraryRefreshCallback");
}
}
//popup onClick
@Override
public void onClick(DialogInterface arg0, int arg1) {
//Created in @see onItemClick
db.deleteFilm(film);
refresh();
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String selectedFromList = (String) (arg0.getItemAtPosition(arg2));
//System.out.println(selectedFromList);
film = new Film();
film.setName(selectedFromList);
System.out.println("DEL: "+film.getName());
//Show popup
ad.show();
return true;
}
片段2:添加(在调用时从片段3显示选项菜单)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_add_film, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().invalidateOptionsMenu();
setHasOptionsMenu(false);
initialize();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
//View init here!
btnSpeichern = (Button) view.findViewById(R.id.btn_add_film_speichern);
btnSpeichern.setOnClickListener(this);
editFilmName = (EditText) view.findViewById(R.id.edit_add_film_name);
}
private void initialize() {
db = new DatabaseHelper(this.getActivity().getApplicationContext());
ad = new AlertDialog.Builder(this.getActivity())
.setTitle("Bestätigung")
.setMessage("Wirklick speichern?")
.setNegativeButton("Nein", null)
.setPositiveButton("Ja", this);
}
@Override
public void onClick(View v) {
hideSoftKeyboard();
ad.show();
}
private void hideSoftKeyboard() {
imm = (InputMethodManager)getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editFilmName.getWindowToken(), 0);
}
@Override
public void onClick(DialogInterface arg0, int arg1) {
db.addFilm(editFilmName.getText().toString());
//Film added; return to library.
callback.onFilmAdded();
}
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
menu.removeItem(R.menu.kiste_random_film);
//inflater.inflate(R.menu.kiste_main, menu);
/*
* ActionBar will display the TrashBin because it
* prepares the next fragment (with its actionbar items)
*
* TODO
* find a way to hide
*/
super.onCreateOptionsMenu(menu,inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
public interface FilmAddedListener {
public void onFilmAdded();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks
try{
callback = (FilmAddedListener) activity;
}catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FilmAddedListener");
}
}
public void setUserVisibibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(this.isVisible()) {
if(!isVisibleToUser) {
hideSoftKeyboard();
}
}
}
片段3:哪个有OptionMenu
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_zufalls_film, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
//View init here!
viewFilm = (TextView) view.findViewById(R.id.zufallsfilm_zufallsfilm);
viewFilm.setText(film.getName().toString());
}
private void initialize() {
db = new DatabaseHelper(this.getActivity().getApplicationContext());
poolIDs = db.getAvailableFilmIDs();
r = new Random();
Log.i("POOL_SIZE",""+poolIDs.size());
randNum = r.nextInt(poolIDs.size());
Log.i("RANDOM_GEN",""+randNum);
film = db.getFilm(poolIDs.get(randNum));
ad = new AlertDialog.Builder(this.getActivity())
.setTitle("Löschen?")
.setMessage("Der Film sollte nur gelöscht werden, wenn es keinen weiteren Teil gibt.")
.setNegativeButton("Nein", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callback.onReturn();
}
})
.setPositiveButton("Ja", this);
ai = new AlertDialog.Builder(this.getActivity())
.setTitle("Status")
.setNeutralButton("OK", null);
}
private void handleBack() {
ad.show();
}
@Override
public void onClick(DialogInterface arg0, int arg1) {
db.deleteFilm(film); //Can return boolean @see del
callback.onFilmDeleted(film.getName());
}
@Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
handleBack();
return true;
}
return false;
}
});
//To enable ActionBarItems
if(isVisible()) {
setHasOptionsMenu(true);
getActivity().invalidateOptionsMenu();
}
}
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if(isVisible()) {
inflater.inflate(R.menu.kiste_random_film, menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
//isVisible() doesn't work the way I expected it.
if(isVisible()) {
switch (item.getItemId()) {
case R.id.action_delete:
handleBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
return super.onOptionsItemSelected(item);
}
public interface FilmDeletedListener {
void onFilmDeleted(String name);
void onReturn();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks
try{
callback = (FilmDeletedListener) activity;
}catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FilmDeletedListener");
}
}
来自MyPagerAdapter的getItem(..)方法(扩展FragmentStatePagerAdapter)
@Override
public Fragment getItem(int index) {
Log.d("MPA","SWITCHED TO POS "+ index);
switch(index) {
case 0:
Log.d("MPA","RETURN LIB");
return new LibraryFragment();
case 1:
Log.d("MPA","RETURN NEW");
return new SomethingNewFragment();
case 2:
Log.d("MPA","RETURN RAN");
return new ForGreatEntertainmentFragment();
}
return null;
}