Ustawianie własnego tytułu paska akcji z fragmentu

W Moim głównym FragmentActivity, ustawiam swój własny ActionBar tytuł tak:

    LayoutInflater inflator = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflator.inflate(R.layout.custom_titlebar, null);

    TextView tv = (TextView) v.findViewById(R.id.title);
    Typeface tf = Typeface.createFromAsset(this.getAssets(),
            "fonts/capsuula.ttf");
    tv.setTypeface(tf);
    tv.setText(this.getTitle());

    actionBar.setCustomView(v);
To działa idealnie. Jednak gdy otworzę inne Fragments, chcę zmienić tytuł. Nie jestem pewien, jak uzyskać dostęp do głównego Activity, aby to zrobić? W przeszłości robiłem to:
((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
            catTitle);
Czy ktoś może doradzić w sprawie właściwej metody?

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text=""
        android:textColor="#fff"
        android:textSize="25sp" />

</RelativeLayout>
Author: KickingLettuce, 2013-03-22

19 answers

W Twojej aktywności:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

A w Twoim fragmencie:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // Set title bar
    ((MainFragmentActivity) getActivity())
            .setActionBarTitle("Your title");

}

===Aktualizacja Kwiecień, 10, 2015===

Powinieneś użyć listenera, aby zaktualizować tytuł paska akcji

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);
}

}

I Aktywność:

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);
}

}

Czytaj więcej tutaj: https://developer.android.com/training/basics/fragments/communicating.html

 60
Author: Frank Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-20 03:34:55

To co robisz jest poprawne. Fragments nie masz dostępu do API ActionBar, więc musisz zadzwonić getActivity. Chyba że twoja Fragment jest statyczną klasą wewnętrzną, w takim przypadku powinieneś utworzyć {[6] } do rodzica i wywołać aktywność.Stamtąd.

Aby ustawić tytuł dla twojego ActionBar, podczas korzystania z niestandardowego układu, w twoim Fragment musisz wywołać getActivity().setTitle(YOUR_TITLE).

Powodem, dla którego dzwonisz setTitle jest to, że dzwonisz {[12] } jako tytuł swojego ActionBar. getTitle zwraca tytuł dla tego Activity.

Jeśli nie chcesz uzyskać wywołania getTitle, musisz utworzyć metodę publiczną, która ustawia tekst twojego TextView w Activity, która hostuje Fragment.

W Twojej aktywności :

public void setActionBarTitle(String title){
    YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);
}

W Twoim fragmencie :

((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);

Docs:

Activity.getTitle

Activity.setTitle

Poza tym, nie musisz dzwonić this.whatever w podanym kodzie, tylko wskazówka.

 143
Author: adneal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-22 16:30:16

Przykłady Google mają tendencję do używania tego we fragmentach.

private ActionBar getActionBar() {
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

Fragment będzie należał do ActionBarActivity i tam znajduje się odniesienie do actionbara. Jest to czystsze, ponieważ fragment nie musi dokładnie wiedzieć, jaka to aktywność, musi jedynie należeć do aktywności, która implementuje ActionBarActivity. To sprawia, że fragment jest bardziej elastyczny i może być dodawany do wielu działań, tak jak są one przeznaczone.

Teraz wszystko, co musisz zrobić we fragmencie jest.

getActionBar().setTitle("Your Title");

Działa to dobrze, jeśli masz fragment bazowy, od którego dziedziczą Twoje fragmenty zamiast normalnej klasy fragment.

public abstract class BaseFragment extends Fragment {
    public ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }
}

Następnie w Twoim fragmencie.

public class YourFragment extends BaseFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getActionBar().setTitle("Your Title");
    }
}
 25
Author: Kalel Wade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-09 15:06:12

Ustawienie tytułu Activity z Fragment psuje poziom odpowiedzialności. {[3] } jest zawarte w Activity, więc jest to Activity, który powinien ustawić swój własny tytuł zgodnie z typem Fragment na przykład.

Załóżmy, że masz interfejs:

interface TopLevelFragment
{
    String getTitle();
}

Te Fragment, które mogą wpływać na tytuł Activity, następnie zaimplementują ten interfejs. Podczas gdy w działalności hostingowej piszesz:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fm = getFragmentManager();
    fm.beginTransaction().add(0, new LoginFragment(), "login").commit();
}

@Override
public void onAttachFragment(Fragment fragment)
{
    super.onAttachFragment(fragment);

    if (fragment instanceof TopLevelFragment)
        setTitle(((TopLevelFragment) fragment).getTitle());
}

W ten sposób Activity jest zawsze pod kontrolą, jakiego tytułu używać, nawet jeśli kilka TopLevelFragmentS są połączone, co jest całkiem możliwe na tablecie.

 6
Author: Aleks N.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-23 09:17:28

W fragmencie możemy użyć tak, to działa dobrze dla mnie.

getActivity().getActionBar().setTitle("YOUR TITLE");
 5
Author: NagarjunaReddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 08:27:39

Na wszelki wypadek, jeśli masz problemy z kodem, spróbuj umieścić getSupportActionBar().setTitle(title) wewnątrz onResume() swojego fragmentu zamiast onCreateView(...) tj.]}

W Głównej Aktywności.java :

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

We Fragmencie:

 @Override
 public void onResume(){
     super.onResume();
     ((MainActivity) getActivity()).setActionBarTitle("Your Title");
 }
 3
Author: realpac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-04 14:52:20

Użyj następującego:

getActivity().setTitle("YOUR_TITLE");
 2
Author: Anisetti Nagendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-11 05:43:23

Nie sądzę, aby zaakceptowana odpowiedź była na to idealna. Ponieważ wszystkie działania, które używają

Pasek narzędzi

Są rozszerzane za pomocą

AppCompatActivity

, fragmenty wywołane z niego mogą użyć poniższego kodu do zmiany tytułu.

((AppCompatActivity) context).getSupportActionBar().setTitle("Your Title");
 2
Author: Manoj Perumarath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-16 10:20:47

Jeśli masz główną aktywność z wieloma fragmentami, które wstawiasz, zwykle za pomocą navigationDrawer. I masz szereg tytułów dla swoich fragmentów, kiedy naciśniesz Wstecz, aby je zmienić, umieść to w głównej actity, które przechowują fragmenty

@Override
     public void onBackPressed() {

    int T=getSupportFragmentManager().getBackStackEntryCount();
    if(T==1) { finish();}

    if(T>1) {
        int tr = Integer.parseInt(getSupportFragmentManager().getBackStackEntryAt(T-2).getName());
        setTitle(navMenuTitles[tr]);  super.onBackPressed();
      }

}

Zakłada się, że dla każdego fragmentu nadajesz mu tag, zwykle gdzieś po dodaniu fragmentów do listy navigationDrawer, zgodnie z pozycją wciśniętą na liście. Więc ta pozycja jest tym, co uchwyciłem na tag:

    fragmentManager.beginTransaction().
replace(R.id.frame_container, fragment).addToBackStack(position).commit();

Teraz, navMenuTitles jest coś ładować na onCreate

 // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

Tablica XML jest zasobem typu array string na łańcuchach.xml

 <!-- Nav Drawer Menu Items -->
    <string-array name="nav_drawer_items">
        <item>Title one</item>
        <item>Title Two</item>
    </string-array>
 1
Author: Miguel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-07 14:12:56

Zapisz odpowiedź ur w obiekcie String [] i ustaw ją OnTabChange () w MainActivity jako poniżej www

String[] object = {"Fragment1","Fragment2","Fragment3"};

public void OnTabChange(String tabId)
{
int pos =mTabHost.getCurrentTab();     //To get tab position
 actionbar.setTitle(object.get(pos));
}


//Setting in View Pager
public void onPageSelected(int arg0) {
    mTabHost.setCurrentTab(arg0);
actionbar.setTitle(object.get(pos));
}
 1
Author: Narendra Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-13 03:58:43

Oto moje rozwiązanie do ustawiania tytułu ActionBar z fragmentów, podczas korzystania z NavigationDrawer. To rozwiązanie wykorzystuje interfejs, więc fragmenty nie muszą odwoływać się bezpośrednio do aktywności rodzica:

1) Utwórz interfejs:

public interface ActionBarTitleSetter {
    public void setTitle(String title); 
}

2) w fragmencie onAttach , Wrzuć aktywność do typu interfejsu i wywołaj metodę SetActivityTitle:

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity);
    ((ActionBarTitleSetter) activity).setTitle(getString(R.string.title_bubbles_map)); 
}

3) w działaniu zaimplementuj interfejs ActionBarTitleSetter :

@Override 
public void setTitle(String title) { 
    mTitle = title; 
}
 1
Author: Assaf S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-02 13:57:04

Minusem twojego podejścia do rzucania w ten sposób

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
        catTitle);

Jest to, że Twój fragment nie jest już wielokrotnego użytku poza MainActivityFragment. Jeśli nie planujesz używać go poza tą aktywnością, nie ma problemu. Lepsze podejście byłoby warunkowo ustawić tytuł w zależności od działalności. Więc w Twoim fragmencie napiszesz:

if (getActivity() instanceof ActionBarActivity) {
    ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Some Title");
}
 1
Author: Mieczysław Daniel Dyba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-18 17:24:30

Jeśli używasz android studio 1.4 stabilny szablon dostarczony przez google niż prosty trzeba było napisać następujący kod w onNavigationItemSelected methode w którym powiązany fragment wywołuje warunek if.

 setTitle("YOUR FRAGMENT TITLE");
 1
Author: Manan Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-19 11:06:09

Otrzymuję bardzo proste rozwiązanie, aby ustawić ActionBar Title w albo fragment lub jakąkolwiek aktywność bez bólu głowy.

Wystarczy zmodyfikować XML gdzie jest zdefiniowany pasek narzędzi jak poniżej:

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimaryDark"
            app:popupTheme="@style/AppTheme.PopupOverlay" >

            <TextView
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:id="@+id/toolbar_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                />
            </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout> 

1) jeśli chcesz ustawić actionbar we fragmencie, to:

Toolbar toolbar = findViewById(R.id.toolbar);
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

Aby używać go z dowolnego miejsca, możesz zdefiniować metodę w ćwiczeniu

public void setActionBarTitle(String title) {
        toolbarTitle.setText(title);
    }

Aby wywołać tę metodę w activity, wystarczy wywołać to.

setActionBarTitle("Your Title")

Aby wywołać tę metodę z fragmentu aktywności, po prostu ją wywołaj.

((MyActivity)getActivity()).setActionBarTitle("Your Title");
 1
Author: JoboFive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-23 10:23:19

Aby dodać do wybranej odpowiedzi, Możesz również dodać drugą metodę do głównego działania. Tak więc w Twoim głównym działaniu znajdziesz następujące metody:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

public void setActionBarTitle(int resourceId) {
    setActionBarTitle(getResources().getString(resourceId);
}

To pozwoli Ci ustawić tytuł zarówno ze zmiennej łańcuchowej, jak i ID zasobu, takiego jak R.id.this_is_a_string z Twoich łańcuchów.plik xml. Będzie to również działać trochę bardziej jak getSupportActionBar().setTitle() działa, ponieważ pozwala na podanie identyfikatora zasobu.

 0
Author: CodyEngel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-01 17:45:05

Istnieje wiele sposobów, jak opisano powyżej. Można to również zrobić w onNavigationDrawerSelected() w swoim DrawerActivity

public void setTitle(final String title){
    ((TextView)findViewById(R.id.toolbar_title)).setText(title);
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    fragment = null;
    String title = null;
    switch(position){

    case 0:
        fragment = new HomeFragment();
        title = "Home";
        break;
    case 1:
        fragment = new ProfileFragment();
        title = ("Find Work");
        break;
    ...
    }
    if (fragment != null){

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager
        .beginTransaction()
        .replace(R.id.container,
                fragment).commit();

        //The key is this line
        if (title != null && findViewById(R.id.toolbar_title)!= null ) setTitle(title);
    }
}
 0
Author: tricknology,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-16 04:41:07

Przynajmniej dla mnie, była łatwa odpowiedź (po długim kopaniu) na zmianę tytułu karty w czasie wykonywania:

TabLayout tabLayout = (TabLayout) findViewById (R. id.tabs); tabLayout.getTabAt (MyTabPos).setText ("mój nowy tekst");

 0
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-17 15:37:49

Jeśli używasz ViewPager (Jak w moim przypadku) możesz użyć:

getSupportActionBar().setTitle(YOURE_TAB_BAR.getTabAt(position).getText());

In onPageSelected method of your VIEW_PAGER.addOnPageChangeListener

 0
Author: Reza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-24 13:37:06

Best event for change title onCreateOptionsMenu

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.general, container,  
    setHasOptionsMenu(true); // <-Add this line
    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // If use specific menu
    menu.clear();
    inflater.inflate(R.menu.path_list_menu, menu);
    // If use specific menu

    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Fragment");
    super.onCreateOptionsMenu(menu, inflater);
}
 0
Author: Ahmad Aghazadeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 08:49:49