2016-10-05 110 views
1
setDisplayHomeAsUpEnabled

我找遍了所有的一天通過所有類似的問題和答案,在這裏計算器,卻發現不知道爲什麼它不工作onOptionsItemSelected不叫片段與AppCompatActivity

這裏從我的代碼的一些摘錄

片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    rootView = inflater.inflate(R.layout.fragment_gallery, container, false); 
    setHasOptionsMenu(true); 
    actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar(); 
    actionBar.setTitle("Portfolio"); 
    updateGallery(); 
    return rootView; 
} 


    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    super.onCreateOptionsMenu(menu, inflater); 
} 

    public void updateGallery() { 
    if (activeAlbum>0) { 
     actionBar.setDisplayHomeAsUpEnabled(true); 
    } else { 
     actionBar.setDisplayHomeAsUpEnabled(false); 
    } 
...... 
} 

    @Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     default: 
      break; 
    } 
    return false; 
} 

MainActivity:

public class MainActivity extends AppCompatActivity {...} 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

.... 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.addDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 


...... 
} 


    public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

onOptionsItemSelected既未在MainActivity中也未在片段中被觸發

回答

0

片段必須聲明它們可以提供選項。看看這裏:

https://developer.android.com/reference/android/app/Fragment.html#setHasOptionsMenu(boolean)

我想你只需要調用setHasOptionsMenu(真)在onCreateView()的片段中。

+0

感謝你的鏈接,我會看看 (我已經打電話setHasOptionsMenu(真)) 我擔心別的東西可以用onOptionsItemSelected 被幹擾(也許我應該嘗試添加一個新的「空「片段進行測試) – jthomas

相關問題