0

我的工具欄按鈕沒有顯示在我試過的片段中setHasOptionsMenu(true);。當我點擊導航抽屜項目時,它會爲每個片段加載新片段,我想要顯示不同的操作欄按鈕(通知或保存)。以下是我的代碼,預先感謝。Actionbar按鈕沒有顯示在片段

以下是我片段碼:(這是相同的導航抽屜所有碎片)

public class Company1 extends Fragment { 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setHasOptionsMenu(true); 
    } 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.fragment_company_profile,container, false); 

    init(view); 

    btnAdd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      showAddDialog(); 
     } 
    }); 


    return view; 
} 

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.company_profile, menu); 
    super.onCreateOptionsMenu(menu, inflater); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.notification: 
      break; 

    } 
    return super.onOptionsItemSelected(item); 
} 

} 

這是company_profile.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" > 

    <item 
     android:id="@+id/notification" 
     android:icon="@drawable/ic_action_notification" 
     android:title="@string/mnuNotificationText" 
     app:showAsAction="always"/> 
    </menu> 
+0

I它沒有出現在任何片段中,或者只在某些情況下(沒有更新等)? – Shaishav

+0

不是所有帶導航抽屜的片段。 – Harshad07

回答

1

請檢查此代碼段

public class Company1 extends Fragment { 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    } 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.fragment_company_profile,container, false); 
    setHasOptionsMenu(true); 
    init(view); 

    btnAdd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      showAddDialog(); 
     } 
    }); 


    return view; 
} 

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.company_profile, menu); 
    super.onCreateOptionsMenu(menu, inflater); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.notification: 
      break; 

    } 
    return super.onOptionsItemSelected(item); 
} 
@Override 
    public void onPrepareOptionsMenu(Menu menu) { 
     //You can change menuitem property 
     //menu.findItem(R.id.notification).setVisible(true); 
     super.onPrepareOptionsMenu(menu); 

    } 
}