gpt4 book ai didi

android - 使用 fragment 将图像添加到选项卡

转载 作者:行者123 更新时间:2023-11-29 15:57:05 24 4
gpt4 key购买 nike

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

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

最佳答案

请参阅此链接: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));
}

关于android - 使用 fragment 将图像添加到选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27446647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com