Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionBar (Support) with Fragment (support)

I need to use a combination of action bar and fragments in one of my android applications that targets Gingerbread too. So I have used the action bar from the v7 support library and fragments from the v4 support library and extend my class with FragmentActivity.

I get an error when I type out the line

actionbar = getSupportActionBar();

The error states that getSupportActionBar() is undefined for the type myFragmentClass (my class name). The code works perfectly without the support library. Is there a solution to my problem?

Thanks!

like image 905
Anirudh Avatar asked Sep 27 '13 13:09

Anirudh


People also ask

How to use Action bar in fragment android?

Contributing to the action bar with fragments. Fragments can also contribute entries to the toolbar bar. To do this, call setHasOptionsMenu(true) in the onCreate() method of the fragment. The Android framework calls in this case the onCreateOptionsMenu() method in the fragment class.

How to add toolbar in fragment?

if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below. ImageView vRightBtn = activity. toolbar.

What is AppBar in android?

The app bar, also known as the action bar, is one of the most important design elements in your app's activities, because it provides a visual structure and interactive elements that are familiar to users.


1 Answers

write this code in OnAttach() method:

actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();

ActionBarActivity is deprecated. Use

actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();

like image 83
bGorle Avatar answered Oct 27 '22 10:10

bGorle