【问题标题】:How to create Tabs in Android Application and add Tabs dynamically(Dependent on matching Users)如何在 Android 应用程序中创建选项卡并动态添加选项卡(取决于匹配的用户)
【发布时间】:2013-07-18 11:47:41
【问题描述】:
我正在 Android 中开发聊天应用程序,我想根据当前匹配的用户添加动态聊天选项卡,如下面的屏幕截图所示:
在屏幕截图中,聊天标签位于顶部,但我想要Chat Tabs at bottom。现在我想在onCreate method 中开发逻辑以便
如果有 3 个匹配的用户,则创建 3 个标签,
如果有四个匹配的用户,则创建 4 个选项卡,同样...
我搜索了很多聊天标签,并找到了使用TabHost..但也发现它已被弃用,不确定..另一种方法是在Action Bar..某处设置聊天标签发现使用ActionBarSherlock。我对使用什么聊天标签感到很困惑?
任何帮助将不胜感激。
【问题讨论】:
标签:
android
tabs
android-actionbar
chat
android-tabhost
【解决方案1】:
@SuppressWarnings("deprecation")
public class MainActivity extends TabActivity {
public static TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tab_main);
// call addtab() how many times you need and pass tag and image resource id
}
private void addTab(String tag, int drawableId) {
tabHost = getTabHost();
TabHost.TabSpec spec = tabHost.newTabSpec(tag);
// tab_indicator layout contains only imageview. this is for fix image size, position
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, getTabWidget(), false);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
tabHost.addTab(spec);
}
}
【解决方案2】:
现在在最新版本的 android 中包含 ActionBarSherlock 库。所以你可以直接在android中使用该库添加标签。
示例代码:
try
{
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText(R.string.firsttab).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.second).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.third).setTabListener(this));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
}
catch(Exception e)
{
e.printStackTrace();
}