如何将标签放入工具栏

时间:2014-12-15 14:02:46

标签: android

我实施了NavigationActivity,为NavigationDrawer Activities添加了public abstract class NavigationActivity extends ActionBarActivity { private Toolbar toolbar = null; private DrawerLayout drawerLayout = null; private ActionBarDrawerToggle drawerToggle = null;; private ListView listView = null; private CharSequence drawerTitle = null; private CharSequence title = null; private NavigationDrawerConfiguration navigationConfig = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.navigationConfig = this.getNavigationDrawerConfiguration(); this.setContentView(this.navigationConfig.getMainLayout()); this.toolbar = (Toolbar) this.findViewById(R.id.app_bar); this.drawerLayout = (DrawerLayout) this.findViewById(navigationConfig.getDrawerLayoutId()); this.listView = (ListView) this.findViewById(navigationConfig.getLeftDrawerId()); this.listView.setAdapter(navigationConfig.getBaseAdapter()); this.listView.setOnItemClickListener(new DrawerItemClickListener()); this.drawerTitle = this.getTitle(); this.title = this.getTitle(); this.setSupportActionBar(this.toolbar); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); this.getSupportActionBar().setHomeButtonEnabled(true); this.drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, this.navigationConfig.getDrawerOpenDesc(), this.navigationConfig.getDrawerCloseDesc()) { @Override public void onDrawerClosed(View view) { getSupportActionBar().setTitle(title); invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(drawerTitle); invalidateOptionsMenu(); } }; this.drawerLayout.setDrawerListener(this.drawerToggle); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); this.drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); this.drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen() != null) { boolean drawerOpen = this.drawerLayout.isDrawerOpen(listView); for (int item : this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen()) { menu.findItem(item).setVisible(!drawerOpen); } } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (this.drawerToggle.onOptionsItemSelected(item)) { return true; } else { return false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (this.drawerLayout.isDrawerOpen(this.listView)) { this.drawerLayout.closeDrawer(this.listView); } else { this.drawerLayout.openDrawer(this.listView); } return true; } return super.onKeyDown(keyCode, event); } protected NavigationDrawerConfiguration getNavigationDrawerConfiguration() { NavigationDrawerItem[] menu = new NavigationDrawerItem[] { // NavigationMenuSection.create(100, "Demos"), NavigationMenuItem.create(100, this.getResources().getString(R.string.title_activity_measurement), "ic_measure", false, this), NavigationMenuItem.create(200, this.getResources().getString(R.string.title_activity_measuredata_list), "ic_list", false, this), // NavigationMenuSection.create(200, "General"), NavigationMenuItem.create(300, this.getResources().getString(R.string.title_activity_diagrams), "ic_diagrams", false, this), NavigationMenuItem.create(400, this.getResources().getString(R.string.title_activity_calc), "ic_calculator", false, this), NavigationMenuItem.create(500, this.getResources().getString(R.string.title_activity_recipe), "ic_scanner", false, this), NavigationMenuItem.create(600, this.getResources().getString(R.string.title_activity_profile), "ic_profile", false, this), NavigationMenuItem.create(700, this.getResources().getString(R.string.title_activity_follower), "ic_follower", false, this), NavigationMenuItem.create(800, this.getResources().getString(R.string.title_activity_settings), "ic_settings", false, this) }; NavigationDrawerConfiguration navigationDrawerConfiguration = new NavigationDrawerConfiguration(); navigationDrawerConfiguration.setMainLayout(R.layout.activity_menu_slide); navigationDrawerConfiguration.setDrawerLayoutId(R.id.menu_slide_layout); navigationDrawerConfiguration.setLeftDrawerId(R.id.menu_slide_list); navigationDrawerConfiguration.setNavigationItems(menu); navigationDrawerConfiguration.setDrawerOpenDesc(R.string.open_navigation_drawer); navigationDrawerConfiguration.setDrawerCloseDesc(R.string.close_navigation_drawer); navigationDrawerConfiguration.setBaseAdapter(new NavigationDrawerAdapter(this, R.layout.activity_menu_slide_item_row, menu)); return navigationDrawerConfiguration; } public void selectItem(int position) { NavigationDrawerItem selectedItem = this.navigationConfig.getNavigationItems()[position]; this.onNavigationItemSelected(selectedItem.getId()); this.listView.setItemChecked(position, true); if (selectedItem.updateActionBarTitle()) { this.setTitle(selectedItem.getLabel()); } if (this.drawerLayout.isDrawerOpen(this.listView)) { this.drawerLayout.closeDrawer(this.listView); } } protected void onNavigationItemSelected(int id) { Intent intent = null; switch ((int) id) { case 100: intent = new Intent(this, MeasureDataActivity.class); break; case 200: intent = new Intent(this, MeasureDataListActivity.class); break; case 300: intent = new Intent(this, DiagramsActivity.class); break; case 400: intent = new Intent(this, CalcActivity.class); break; case 500: intent = new Intent(this, RecipeActivity.class); break; case 600: intent = new Intent(this, ProfileActivity.class); break; case 700: intent = new Intent(this, FollowerActivity.class); break; case 800: intent = new Intent(this, SettingsActivity.class); break; } intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.startActivity(intent); } protected int getDrawerIcon() { return R.drawable.ic_navigation_drawer; } protected DrawerLayout getDrawerLayout() { return this.drawerLayout; } protected ActionBarDrawerToggle getDrawerToggle() { return this.drawerToggle; } @Override public void setTitle(CharSequence title) { this.title = title; this.getSupportActionBar().setTitle(title); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } }

Toolbar

正如您所见,我使用了新的Fragment。以下代码显示了使用SlidingTabLayout的<{1}}:

public class DiagramsFragment extends Fragment {
    private SlidingTabLayout slidingTabLayout;
    private ViewPager viewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_diagrams, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        this.viewPager = (ViewPager) view.findViewById(R.id.diagrams_pager);
        this.viewPager.setId(0x1000);
        this.viewPager.setAdapter(new DiagramsPagerAdapter(this.getFragmentManager()));
        this.slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.diagrams_tab_layout);
        this.slidingTabLayout.setViewPager(this.viewPager);
    }
}

public class SlidingTabLayout extends HorizontalScrollView {
    private static final int TITLE_OFFSET_DIPS = 24;
    private static final int TAB_VIEW_PADDING_DIPS = 16;
    private static final int TAB_VIEW_TEXT_SIZE_SP = 12;

    public interface TabColorizer {
        int getIndicatorColor(int position);
        int getDividerColor(int position);
    }

    private int titleOffset;
    private int tabViewLayoutId;
    private int tabViewTextViewId;
    private ViewPager viewPager;
    private ViewPager.OnPageChangeListener pageChangeListener;
    private final SlidingTabStrip tabStrip;

    public SlidingTabLayout(Context context) {
        this(context, null);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        this.setHorizontalScrollBarEnabled(false);
        this.setFillViewport(true);
        this.titleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
        this.tabStrip = new SlidingTabStrip(context);

        this.addView(this.tabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

    public void setCustomTabColorizer(TabColorizer tabColorizer) {
        this.tabStrip.setCustomTabColorizer(tabColorizer);
    }

    public void setSelectedIndicatorColors(int... colors) {
        this.tabStrip.setSelectedIndicatorColors(colors);
    }

    public void setDividerColors(int... colors) {
        this.tabStrip.setDividerColors(colors);
    }

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        this.pageChangeListener = listener;
    }

    public void setCustomTabView(int layoutResId, int textViewId) {
        this.tabViewLayoutId = layoutResId;
        this.tabViewTextViewId = textViewId;
    }

    public void setViewPager(ViewPager viewPager) {
        this.tabStrip.removeAllViews();

        this.viewPager = viewPager;

        if (this.viewPager != null) {
            this.viewPager.setOnPageChangeListener(new InternalViewPagerListener());
            this.populateTabStrip();
        }
    }

    protected TextView createDefaultTabView(Context context) {
        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            TypedValue outValue = new TypedValue();

            this.getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);

            textView.setBackgroundResource(outValue.resourceId);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            textView.setAllCaps(true);
        }

        int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);

        textView.setPadding(padding, padding, padding, padding);

        return textView;
    }

    private void populateTabStrip() {
        final PagerAdapter adapter = this.viewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (this.tabViewLayoutId != 0) {
                tabView = LayoutInflater.from(this.getContext()).inflate(this.tabViewLayoutId, this.tabStrip, false);
                tabTitleView = (TextView) tabView.findViewById(this.tabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(this.getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);

            this.tabStrip.addView(tabView);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (this.viewPager != null) {
            this.scrollToTab(this.viewPager.getCurrentItem(), 0);
        }
    }

    private void scrollToTab(int tabIndex, int positionOffset) {
        final int tabStripChildCount = this.tabStrip.getChildCount();

        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        View selectedChild = this.tabStrip.getChildAt(tabIndex);

        if (selectedChild != null) {
            int targetScrollX = selectedChild.getLeft() + positionOffset;

            if (tabIndex > 0 || positionOffset > 0) {
                targetScrollX -= this.titleOffset;
            }

            this.scrollTo(targetScrollX, 0);
        }
    }

    private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
        private int scrollState = -1;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int tabStripChildCount = tabStrip.getChildCount();

            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            tabStrip.onViewPagerPageChanged(position, positionOffset);

            View selectedTitle = tabStrip.getChildAt(position);
            int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWidth()) : 0;

            scrollToTab(position, extraOffset);

            if (pageChangeListener != null) {
                pageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            this.scrollState = state;

            if (pageChangeListener != null) {
                pageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (this.scrollState == ViewPager.SCROLL_STATE_IDLE) {
                tabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }

            if (pageChangeListener != null) {
                pageChangeListener.onPageSelected(position);
            }
        }

    }

    private class TabClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < tabStrip.getChildCount(); i++) {
                if (view == tabStrip.getChildAt(i)) {
                    viewPager.setCurrentItem(i);

                    return;
                }
            }
        }
    }
}

创建的Tabs位于工具栏下方。如何将标签放在工具栏中? 我的问题是工具栏+标签在水平方向占用了太多的屏幕空间 方向,所以我希望它们放在工具栏中。

如何实现?

0 个答案:

没有答案