使用片段将图像添加到选项卡

时间:2014-12-12 15:18:03

标签: android android-layout android-fragments android-xml android-tabs

我有3个不同的标签,每个标签都有文字。现在我想了解如何在选项卡的文本顶部添加可绘制图像。我知道这可以使用tabhosts,但已被弃用。我的课程如下:

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };

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

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

}

1 个答案:

答案 0 :(得分:4)

请参阅此链接:http://developer.android.com/reference/android/app/ActionBar.Tab.html#setIcon%28android.graphics.drawable.Drawable%29

示例代码:

actionBar.addTab(actionBar.newTab().setText(tab_name).setIcon(R.drawable.tab_icon).setTabListener(this));

但请考虑:  不建议使用操作栏导航模式,内联工具栏操作栏不支持。请考虑使用其他常见的导航模式。 (http://developer.android.com/design/patterns/navigation.html


修改 对于您的代码,您可以执行以下操作:

像标题一样创建图标:

// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
//make sure this has the same length as tabs-array!
private int[] icons = {R.drawable.tab_rated, R.drawable.tab_games, R.drawable.tab_movies} 

将它们添加到循环中:

// Adding Tabs
for (int i = 0; i < tabs.length; i++) {
   actionBar.addTab(actionBar.newTab().setText(tabs[i]).setIcon(icons[i]).setTabListener(this));
}