简体   繁体   中英

set Up Android Toolbar in Fragment Activity

I have one Activity which extends FragmentActivity. I have two fragments, two tabs. I include in the layout a toolbar . What is to use the same toolbar for the two fragments.

1- As i extends Fragments Activity , I don't know what to put in place of setSupportActionBar(toolbar);

2- I want also to add menu to my action .

I try to do those thing but not working My code

public class List extends FragmentActivity {

private Toolbar toolbar;
private ViewPager mPager = null;
private TabLayout mTab = null;

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

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    toolbar.setTitle("MYAPP");

    mPager = (ViewPager) findViewById(R.id.pager);
    mTab = (TabLayout) findViewById(R.id.tabLayout);
    FragmentManager fragmentManager = getSupportFragmentManager();
    mPager.setAdapter(new MyAdapter(fragmentManager));
    mTab.setupWithViewPager(mPager);
}

class MyAdapter extends FragmentStatePagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        if ( position == 0 ){
            fragment = new Fragment1();
        }
        if (position == 1){
            fragment = new Fragment2();
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        if ( position == 0 ){
            return "TITLE 1";
        }
        if ( position == 1 ){
            return "TITLE 2";
        }
        return null;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.events_list_menu, menu);
    return true;
}

}

My menu

<?xml version="1.0" encoding="utf-8"?>

<item
    android:title="recherche"
    android:id="@+id/search"
    android:icon="@drawable/ic_search_white_36dp"
    app:showAsAction="always"
    />

<item
    android:id="@+id/aboutUs"
    android:title="A propos "
    android:icon="@drawable/aboutus"
    app:showAsAction="never"
    />

<item
    android:icon="@drawable/ic_settings_applications_grey600_24dp"
    android:id="@+id/settings"
    android:title="Paramètres"
    app:showAsAction="always"
    />

尝试使用AppCompatActivity

public class List extends AppCompatActivity {...}

use it

Replace FragmentActivity into AppCompatActivity.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM