下面的代码创建了一个带有 4 个选项卡的视图。使用默认主题(在 androidmanifest.xml 中没有定义主题),我得到了第一个图像,其中选项卡平均增长以填充可用空间。如果我将主题设置为android:theme="@android:style/Theme.Holo"
,我会得到第二张图像,其中 tabwidget(具有绿色背景)仍然填充父级的宽度,但选项卡不会增长以填充 tabwidget。
关于如何在使用 Theme.Holo 时获得第一个结果的任何想法?
public class TempProjActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyTabHost(this));
}
private class MyTabHost extends TabHost
{
public MyTabHost(Context context)
{
super(context, null);
setId(android.R.id.tabhost);
TabWidget widget = new TabWidget(getContext());
widget.setId(android.R.id.tabs);
widget.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
widget.setBackgroundColor(Color.GREEN);
FrameLayout layout = new FrameLayout(getContext());
layout.setId(android.R.id.tabcontent);
layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
LinearLayout linearLayout = new LinearLayout(getContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new TabHost.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
linearLayout.addView(widget);
linearLayout.addView(layout);
addView(linearLayout);
setup();
TabSpec spec = newTabSpec("tab1");
spec.setIndicator("", getContext().getResources().getDrawable(R.drawable.ic_launcher));
spec.setContent(new TabContentFactory()
{
@Override
public View createTabContent(String tag)
{
return new View(getContext());
}
});
addTab(spec);
spec = newTabSpec("tab2");
spec.setIndicator("", getContext().getResources().getDrawable(R.drawable.ic_launcher));
spec.setContent(new TabContentFactory()
{
@Override
public View createTabContent(String tag)
{
return new View(getContext());
}
});
addTab(spec);
spec = newTabSpec("tab3");
spec.setIndicator("", getContext().getResources().getDrawable(R.drawable.ic_launcher));
spec.setContent(new TabContentFactory()
{
@Override
public View createTabContent(String tag)
{
return new View(getContext());
}
});
addTab(spec);
spec = newTabSpec("tab5");
spec.setIndicator("", getContext().getResources().getDrawable(R.drawable.ic_launcher));
spec.setContent(new TabContentFactory()
{
@Override
public View createTabContent(String tag)
{
return new View(getContext());
}
});
addTab(spec);
}
}
}
编辑:
如果我在 MyTabHost 的构造函数末尾添加下面的代码,我会得到下图。但是,该图标仍未在选项卡中居中,而且它似乎不是一段特别安全的代码。
有比这更好的选择吗?或者关于这是否是一个合理的选择的意见?
post(new Runnable()
{
@Override
public void run()
{
for(int i = 0; i < widget.getChildCount(); i++)
{
widget.getChildAt(i).getLayoutParams().width = getWidth()/widget.getChildCount();
}
}
});
}