Android Design Support Library - Tablayout with toolbar

时间:2015-07-28 23:29:12

标签: android-studio android-toolbar android-design-library android-optionsmenu android-tablayout

I just made the jump from eclipse to Android Studio and I'm fixing some issues that have come up. One of which is removing the tab navigation offered by ActionBar and switching to the Tablayout offered by AD support library. I have everything up working nicely, but I cannot figure out how to add menu items to the toolbar when specific fragments are on screen.

I think part of the issue is that my MainActivity expands FragmentActivity which takes setActionBar(), and the Toolbar is from the v7 support library - so of course that toolbar is not compatible with that method. I tried setSupportActionBar() but that is not a method found in FragmentActivity - here I'd need to expand ActionBarActivity to access that method, both of which are deprecated (class and method).

So the question remains, how to I make my individual fragments update the options available in the options menu of the toolbar?

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/main_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?android:attr/actionBarSize"
                android:layout_gravity="top"
                android:background="@color/blue"
                app:layout_scrollFlags="scroll|enterAlways"
                app:layout_collapseMode="pin" />

            <android.support.design.widget.TabLayout
                android:id="@+id/main_sliding_tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorColor="@color/blue"
                app:tabMode="fixed" />

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

    <android.support.v4.view.ViewPager
        android:id="@+id/main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white" />

</LinearLayout>

MainActivity.java:

public class MainActivity extends FragmentActivity implements
    TabLayout.OnTabSelectedListener {

    private Toolbar                 mToolbar;
    private ViewPager               mViewPager;
    private TabsPagerAdapter        mTabsPagerAdapter;
    private TabLayout               mTabLayout;

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

        // * unrelated code omitted ...

        // * Initialize main navigation scheme
        mToolbar = (Toolbar)findViewById(R.id.main_toolbar);
        mToolbar.setTitleTextColor(getResources().getColor(R.color.white));
        mToolbar.setLogo(R.drawable.icon_toolbar);

        mViewPager = (ViewPager)findViewById(R.id.main_viewpager);
        mTabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mTabsPagerAdapter);

        mTabLayout = (TabLayout)findViewById(R.id.main_sliding_tabs);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setOnTabSelectedListener(this);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

    }
}

ExampleFragment.java:

public class ExampleFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_athlete, container, false);

        // * unrelated code omitted ...

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // * unrelated code omitted ...
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.example_action_menu, menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // * unrelated code omitted ...
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

Had to change my MainActivity to extend AppCompatActivity instead of FragmentActivity. Then in my themes, change it my style to:

public class MainActivity extends ActionBarActivity {

    private Spinner spinnerMovieSelection;
    private GridView gridViewMovie;
    private MovieAdapter movieAdapter;
    SortByAdapter sortByAdapter;
    private List<Movie> finalMovieList;
    private ImageView ivPoweredBy;
    private ArrayList<String> sortByList;

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

    private void init() {
        finalMovieList = new ArrayList<Movie>();
        sortByList = new ArrayList<String>();
        populateSortByList();

        gridViewMovie = (GridView) findViewById(R.id.gridViewMovie);
        spinnerMovieSelection = (Spinner) findViewById(R.id.spinnerMovieSelection);
        ivPoweredBy = (ImageView) findViewById(R.id.ivPoweredBy);


        sortByAdapter = new SortByAdapter(getApplicationContext(), sortByList);
        movieAdapter = new MovieAdapter(getApplicationContext(), finalMovieList);
        spinnerMovieSelection.setAdapter(sortByAdapter);
        gridViewMovie.setAdapter(movieAdapter);

        spinnerMovieSelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getMovies((String) parent.getItemAtPosition(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void populateSortByList() {
        sortByList.add("Popularity");
        sortByList.add("Highest Rated");
    }

    private void getMovies(String sortBy) {
        Log.e("RANDOM TAG", "GET MOVIES CALLED");
        MovieAsyncTask movieAsyncTask = new MovieAsyncTask() {
            @Override
            public void onResponseReceived(List<Movie> movieList) {
                finalMovieList = movieList;
                movieAdapter.notifyDataSetChanged();
            }
        };
        movieAsyncTask.execute(sortBy);
    }
}

Note the .NoActionBar theme. Things are now working as expected.