Setting Custom ActionBar Title from Fragment
===Update October, 30, 2019===
Since we have new components such as ViewModel and LiveData, we can have a different/easier way to update Activity Title from Fragment by using ViewModel and Live Data
Activity
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow()
}
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.title.observe(this, Observer {
supportActionBar?.title = it
})
} }
MainFragment
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity?.run {
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
} ?: throw Throwable("invalid activity")
viewModel.updateActionBarTitle("Custom Title From Fragment")
} }
And MainModelView:
class MainViewModel : ViewModel() {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
fun updateActionBarTitle(title: String) = _title.postValue(title) }
And then you can update the Activity title from Fragment using viewModel.updateActionBarTitle("Custom Title From Fragment")
===Update April, 10, 2015===
You should use listener to update your action bar title
Fragment:
public class UpdateActionBarTitleFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public UpdateActionBarTitleFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mListener != null) {
mListener.onFragmentInteraction("Custom Title");
}
return inflater.inflate(R.layout.fragment_update_action_bar_title2, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(String title);
}
}
And Activity:
public class UpdateActionBarTitleActivity extends ActionBarActivity implements UpdateActionBarTitleFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_action_bar_title);
}
@Override
public void onFragmentInteraction(String title) {
getSupportActionBar().setTitle(title);
}
}
Read more here: https://developer.android.com/training/basics/fragments/communicating.html
change custom ActionBar title from fragment in android
Create method in your Activity
public void setActionBarTitle(String title) {
mTitle.setText(title); // as you used custom view
}
In SecondFragment
change title in onCreate
or onResume
((YourActivity)getActivity()).setActionBarTitle("Create New Task");
how change Action Bar title from fragment to fragment?
i.e bcoz you not calling restoreActionBar()
function anywhere in your code.
you can change actionbar Title as you navigate from fragment to fragment by like this aswell in onCreateView()
of each Fragment.
ActionBar actionBar = getActivity().getActionBar();
actionBar.setTitle("Your title");
Change ActionBar title using Fragments
In your activity:
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
And in your fragment (You can put it onCreate or onResume):
public void onResume(){
super.onResume();
// Set title bar
((MainFragmentActivity) getActivity())
.setActionBarTitle("Your title");
}
Change ActionBar title from Fragment
I don't know if it's a proper way to do that but you can add a page change listener to your viewpager and in onPageSelected method you can change your title:
yourViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// change your title
// inflate menu
// customize your toolbar
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
How to Change ActionBar title in fragment class in kotlin?
It seems like you're setting the support action bar, so you'd have to use the support action bar in the onCreateView
method too. The actionBar
is null, that's why the code to set the title won't run.
Try this out:
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).supportActionBar?.title = "Example 1"
//...
}
The other problem I think you might run into is that you're adding the support action bar in the activity's onCreate
method, but you're trying to access it in the fragment's onViewCreated
which comes before according to this (I haven't really tried this out, it's just from looking at the diagram). If this is the case, then you'd have to change it. Maybe try the onStart
from the fragment.
Change ActionBar title in the fragments
First create Interface
public interface ToolbarInterface {
public void getToolbarResources(String title, int visibility);
}
Implement it in Your activity
public class NavigationDrawerActivity extends AppCompatActivity
implements ToolbarInterface
And override interface method in activity
@Override
public void getToolbarResources(String title, int visibility) {
getSupportActionBar().setTitle(title);
}
}
In Fragment call interface in Oncreete method like
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ToolbarInterface toolbarCallback = (ToolbarInterface) getActivity();
}
And set title from onCreateView Method like
toolbarCallback.getToolbarResources("Toolbar title",1);
How to change the ActionBar title from the fragment class in Android Studio?
Based on your code you don't need to change action bar title from fragment
you can change inside your switch case
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
String title = "";
switch (position) {
case 0:
fragment = new HomeFragment();
title="Home";
break;
case 1:
fragment = new AccountFragment();
title="Accounts";
break;
}
if (fragment == null) {
fragment = new HomeFragment();
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
getSupportActionBar().setTitle(title);
}
Even if you want to change actionbar from fragment use interface
Create a interface inside fragment
Implement the Interface in Activity
When you want to change actionbar using callback call the interface function in Activity
Dynamic ActionBar title from a Fragment using AndroidX Navigation
As of 1.0.0-alpha08
, you can have the NavigationUI bits dynamically set the title... if the dynamic bits are arguments on the navigation action.
So, for example, in your navigation graph, you could have something like this:
<fragment
android:id="@+id/displayFragment"
android:name="com.commonsware.jetpack.sampler.nav.DisplayFragment"
android:label="Title: {title}" >
<argument
android:name="modelId"
app:argType="string" />
<argument
android:name="title"
app:argType="string" />
</fragment>
Here, the android:label
attribute for our <fragment>
has an argument name wrapped in braces ({title}
in "Title: {title}"
. The app bar's title will then be set to the value of the label, with {title}
replaced by the value of the title
argument.
If you need something more elaborate than that — for example, you want to look up the model by ID and read a property from it — you will need to use more manual approaches, such as those outlined in other answers to this question.
Related Topics
What Is Shareduserid in Android, and How Is It Used
How Do Jps, Jinfo, Jstat, Jmap and Jstack Get Information About Local Java Processes
Library to Read/Write Pbxproj/Xcodeproj Files
What Could Cause Java.Lang.Reflect.Invocationtargetexception
Sockets: Discover Port Availability Using Java
Tracing Xml Request/Responses with Jax-Ws
Connection to Db Dies After >4<24 in Spring-Boot JPA Hibernate
How to Use Xpath on Xml Docs Having Default Namespace
Java: Run a Function After a Specific Number of Seconds
Removing Duplicates from a String in Java
Android.Util.Androidruntimeexception: Requestfeature() Must Be Called Before Adding Content
Check Group Membership for a Linux User Using Java
Ruby and Duck Typing: Design by Contract Impossible
Convert Existing Eclipse Project to Maven Project
Generate All Combinations from Multiple Lists
Running Code After Spring Boot Starts
Parsing a String to Date Format in Java Defaults Date to 1 and Month to January