我實現了一個工具欄,並根據我的需求將其替換爲我的操作欄。現在我想在片段內的工具欄中添加一個圖標。我嘗試了onCreateOptionMenu()並將我的菜單xml傳遞給它。但它不會工作。我也嘗試了一些其他的東西和谷歌搜索,但沒有任何工作到目前爲止。有人對此有任何想法。這裏是我的片段代碼Android在片段內的工具欄中添加圖標
public class Fragment_FavouriteLocations extends Fragment {
public Fragment_FavouriteLocations() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main_fav_location_row_item, container, false);
}
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fav_location_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
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.edit_button) {
Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
return true;
}
//
// if(id == R.id.action_search){
// Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
}
這裏是我的菜單XML提前
沒有設置setSupportActionBar(mToolbar); ? – 3xplore
嘗試過。但無法這樣做。 getActivity()。setSupportedActionBar(mToolbar)不會工作 –
你必須對你的活動做它,你可以發佈你的活動代碼 – 3xplore