On my application I have only one activity (that extends ActionBarActivity ) and various Fragments (that extends Fragment).
When the user click on a menu option, the application change the Fragment.
At this moment I want to change de title and the background color of the ActionBar.
When I try ActionBar actionBar = getActivity().getActionBar(); I got a null exception.
I'm using support library, and on the Activity I'm using android.support.v7.app.ActionBar actionBar = getSupportActionBar(); successfully.
On the Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.material_cadastro, container, false);
viewHolder = new MaterialViewHolder(view);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setTitle(R.string.inserir_material);
return view;
}
Debuging I got that the Activity is returning OK, but the ActionBar is null:
getActivity() = {br.com.americocarelli.vendasfacil.ui.MenuPrincipal#3b56766f}
getActivity().getActionBar() = null
Override your onAttach(Activity), then cast your Activity to ActionBarActivity, the you can get an ActionBar.
Like:
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
ActionBar actionBar=((ActionBarActivity)activity).getSupportActionBar();
}
Since you use the support library (ActionBarActivity), then use ((ActionBarActivity)getActivity()).getSupportActionBar(); to get access to the support action bar.
You are probably building it with build tools >=21, that versions causes activity.getActionBar() returns null, you should use getSupportActionBar() instead.
EDIT: if you get NPE at exactly this line: getActivity(). ... then you are probably referencing it before or after fragment is attached to activity. Could you please paste the context (place, in what function) you are using it?
Related
I am using navigation drawer in my application, with fragments. There are icons and text in each row(one of them is products, on clicking these a fragment is open with a list view.After clicking on the list view row i have an activity in this i want header name same as i have selected(products).but bydefault it is showing name off the app which is sales.please help.
pass product name in Intent in your list's onItemClickListner
Intent intent = new Intent(getActivity(),YOURACTIVITY.class);
intent.putExtra("product_name",YOUR PRODUCT_NAME);
getActivity().startActivity(intent);
and in your target activity (your product detail activity) put below code in onCreate() method.
getSupportActionBar().setTitle("YOUR DESIRED TITLE");
If using Frament , you can have a method in parent hosting Activity like
this
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
and invoke this method from your individual fragment like this and set the title
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//usual statements
((HomeActivity)getActivity()).setActionBarTitle("Child fragment name");
}
You can set the actionbar header with the following. You can try this.
ActionBar actionBar = getActionBar();
actionBar.setTitle("My Title");
good morning every one,
I am using swipe tabs in fragments but getting null action bar.
Code snippet is given below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.ride_detail, container, false);
li = getLayoutInflater(savedInstanceState);
context = getActivity();
customizedToast = new CustomizedToast(context, li);
actionBar = ((ActionBarActivity)getActivity()).getActionBar();
I have also tried with:
actionBar = getActivity().getActionBar();
Thanks.
You should use getSupportActionBar instead of getActionBar if you are working with ActionBarActivity. The getActionBar method is available in the ActionBarActivity API since it extends Activity, but should not be used when working with support Activities.
Check you import which action bar you are importing...
Change Activity theme in Android Manifest to Theme.Holo
I have an application with two fragments when the application starts the Actionbar title is the one of the first fragment. But when I'm going to the second Fragment the title doesn't change.
So how do I change the ActionBar title?
This is my code:
public class ClientList extends Fragment {
#Override
public void onResume() {
super.onResume();
String title;
title = getResources().getString(R.string.client_title);
ActionBarActivity action = ((EmployeeActivity)getActivity());
action.getSupportActionBar().setTitle(title);
}
#Override
public void onDestroyView() {
super.onDestroyView();
String title2;
title2 = getResources().getString(R.string.action_settings);
ActionBarActivity action = ((EmployeeActivity)getActivity());
action.getSupportActionBar().setTitle(title2);
}
}
so if you say you cannot reach the method from onCreateView, so this is your solution I think:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment,
container, false);
getActivity().setTitle("Title");
return view;
}
Because if you return before you call setTitle() you cannot reach it, that's true.
Hope it helps.
You can set your action bar title inside onCreate(if activity)/onCreateView(if fragment) method as getSupportActionBar().setTitle("Your Title");
Whenever you switch from one fragment to another fragment you can set the title in ActionBar. This can be done on onCreateView(...) of a fragment. Advisable try to change the name in Activity in which you are trying to load the fragment.
To do so ....
If you are using appcompat library
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(" your title ");
If you are not using appcompat library
ActionBar actionBar = getActionBar();
actionBar.setTitle(" your title ");
This should work:
getActivity().setTitle(YOUR_TITLE);
Call it from your Fragment when you wanted to set.
I have created a custom action bar which works fine on my starting activity but gives an error when I call the method from other activities in the same application.
This is the code I am using to set the ActionBar in my first activity
firstAct.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBarSetup(this);
}
void actionBarSetup(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setDisplayShowCustomEnabled(true);
ab.setDisplayShowTitleEnabled(false);
ab.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.actionbar_layout, null);
//assign the view to the actionbar
ab.setCustomView(v);
}
}
**secondAct.java**
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_pg);
(new firstAct()).actionBarSetup(secondAct.this);
}
I get NullPointerException when i call actionBarSetup() from secondAct.java
on line ActionBar ab = getActionBar().
Is it that getActionBar() cannot be called directly from other activities besides the main activity ie. firstAct.
How to call it from other Activities then?
You don't create new activities by calling their constructor. You have the system create and open them for you. I'm talking about the line
(new firstAct()).actionBarSetup(secondAct.this)
What are you trying to do here?
You probably want to make the actionBarSetup method accessible for all classes and not just instances of firstAct. Then declare it like this (maybe move it to a utility class?):
public static void actionBarSetup(Activity activity) {
ActionBar ab = activity.getActionBar(); // you need activity, not just context
// ...
}
Then call it from other classes like this:
firstAct.actionBarSetup(this);
Making a method static detaches it from an instances resources. You were taking in second activity (context parameter) but asking for an action bar from instance of the first activity (essentially this.getActionBar()) which was not setup by system (because you misused constructor).
Note: Please use PascalCase notation for class names (capital first letter).
EDIT
Warning: Your action bar may have different styling from your activity (e.g. black toolbar and white activity). In that case using the activity's inflater to inflate contents of the action bar will produce undesired results (inverted text color mainly). The following line is safer. But it's available no sooner than API 14.
LayoutInflater inflator = LayoutInflater.from(ab.getThemedContext());
You need create BaseActivity like
public class BaseActivity extends Activity {
public void actionBarSetup(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setDisplayShowCustomEnabled(true);
ab.setDisplayShowTitleEnabled(false);
ab.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.actionbar_layout, null);
//assign the view to the actionbar
ab.setCustomView(v);
}
}
then you need firstAct and secondAct extend BaseActivity then in onCreate method call actionBarSetup()
This may help
private void showCustoNavBar(){
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.new_gradient));
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
View customNav = LayoutInflater.from(this).inflate(R.layout.actioncustomview, null);
getSupportActionBar().setCustomView(customNav);
}
I'm starting a new project that uses the AppCompat/ActionBarCompat in v7 support library. I'm trying to figure out how to use the getSupportActionBar from within a fragment. My activity that hosts the fragment extends ActionBarActivity, but I don't see a similar support class for Fragments.
From within my fragment
public class CrimeFragment extends Fragment {
//...
getActivity().getSupportActionBar().setSubtitle(R.string.subtitle); // getSupportActionBar is not defined in the v4 version of Fragment
//...
}
The google page for using it (http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html) says there should be no changes for the v4 fragment. Do I need to cast all my getActivity() calls to an ActionBarActivity? That seems like poor design.
After Fragment.onActivityCreated(...) you'll have a valid activity accessible through getActivity().
You'll need to cast it to an ActionBarActivity then make the call to getSupportActionBar().
((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle(R.string.subtitle);
You do need the cast. It's not poor design, it's backwards compatibility.
While this question has an accepted answer already, I must point out that it isn't totally correct: calling getSupportActionBar() from Fragment.onAttach() will cause a NullPointerException when the activity is rotated.
Short answer:
Use ((ActionBarActivity)getActivity()).getSupportActionBar() in onActivityCreated() (or any point afterwards in its lifecycle) instead of onAttach().
Long answer:
The reason is that if an ActionBarActivity is recreated after a rotation, it will restore all Fragments before actually creating the ActionBar object.
Source code for ActionBarActivity in the support-v7 library:
#Override
protected void onCreate(Bundle savedInstanceState) {
mImpl = ActionBarActivityDelegate.createDelegate(this);
super.onCreate(savedInstanceState);
mImpl.onCreate(savedInstanceState);
}
ActionBarActivityDelegate.createDelegate() creates the mImpl object depending on the Android version.
super.onCreate() is FragmentActivity.onCreate(), which restores any previous fragments after a rotation (FragmentManagerImpl.dispatchCreate(), &c).
mImpl.onCreate(savedInstanceState) is ActionBarActivityDelegate.onCreate(), which reads the mHasActionBar variable from the window style.
Before mHasActionBar is true, getSupportActionBar() will always return null.
Source for ActionBarActivityDelegate.getSupportActionBar():
final ActionBar getSupportActionBar() {
// The Action Bar should be lazily created as mHasActionBar or mOverlayActionBar
// could change after onCreate
if (mHasActionBar || mOverlayActionBar) {
if (mActionBar == null) {
... creates the action bar ...
}
} else {
// If we're not set to have a Action Bar, null it just in case it's been set
mActionBar = null;
}
return mActionBar;
}
If someone uses com.android.support:appcompat-v7: and AppCompatActivity as activity then this will work
((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle(R.string.subtitle);
For those using kotlin,
(activity as AppCompatActivity).supportActionBar.setSubtitle(R.string.subtitle)
As an updated answer for Pierre-Antoine LaFayette's answer
ActionBarActivity is deprecated; use AppCompatActivity instead
((AppCompatActivity)getActivity()).getSupportActionBar();
in your fragment.xml add Toolbar Tag from support library
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
Now how we can control it from MyFragment class? let's see
inside onCreateView function add the following
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
//add this line if you want to provide Up Navigation but don't forget to to
//identify parent activity in manifest file
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and if you want to add items to the toolbar within MyFragment
you must add this line inside onCreateView function
setHasOptionsMenu(true);
this line is important, if you forget it, android will not populate your menu Items.
assume we identify them in menu/fragment_menu.xml
after that override the following functions
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_1:
// do stuff
return true;
case R.id.action_2:
// do more stuff
return true;
}
return false;
}
hope this helps
As an addendum to GzDev's answer, if you already have the string, you can use kotlin's auto-setter:
(activity as AppCompatActivity).supportActionBar?.subtitle = my_string
And you can turn it off by simply using an empty string.
Note that this works for both the title and the subtitle.