GetActionBar () - undefined

I want to add an ActionBar to the Fragment class, but I keep getting errors. This is my class:

public class TaskDetailFragment extends Fragment { public static final String ARG_ITEM_ID = "item_id"; MyTasks.taskItem mItem; public TaskDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { mItem = MyTasks.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_task_detail, container, false); ActionBar actionBar = getActionBar(); actionBar.show(); if (mItem != null) { //Add TexViews ((TextView) rootView.findViewById(R.id.in_Name)) .setText(MyTasks.customers[(Integer.parseInt(mItem.id))][1]); ((TextView) rootView.findViewById(R.id.in_Address)) .setText(MyTasks.customers[(Integer.parseInt(mItem.id))][3] + " " + MyTasks.customers[(Integer.parseInt(mItem.id))][2]); } return rootView; } } 

That's my fault:

The getActionBar () method is undefined for the type TaskDetailFragment

+4
source share
3 answers

As far as I know, you need to set the Activity (to which the Fragment attached) for the ActionBar :

 ActionBar actionBar = getActivity().getActionBar(); 

Or, if you use the support library and / or ActionBarSherlock:

 ActionBar actionBar = getFragmentActivity().getSupportActionBar(); 

Fragments do not define the getActionBar() method, therefore an error message.

+12
source

make sure getActionBar () is defined in TaskDetailFragment or other superclasses or sometimes android emulataor can add β€œprotected” to the method definition

0
source

If a fragment wants to use an ActionBar, it should call setHasOptionsMenu(true) , usually from onCreate() .

0
source

Source: https://habr.com/ru/post/1442605/


All Articles