以下是我创建tabhost的方法,我想要做的是在用户单击选项卡时获取选项卡。问题是,它返回null而不是标记值。
tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
tabHost.addTab(
tabHost.newTabSpec("home").setIndicator("",
getResources().getDrawable(R.drawable.meun_home)),
HomeFragment.class, null);
tabHost.addTab(
tabHost.newTabSpec("form").setIndicator("",
getResources().getDrawable(R.drawable.meun_register)),
FormFragment.class, null);
tabHost.addTab(
tabHost.newTabSpec("calculator").setIndicator("",
getResources().getDrawable(R.drawable.meun_calculator)),
CalculatorFragment.class, null);
tabHost.addTab(
tabHost.newTabSpec("news").setIndicator("",
getResources().getDrawable(R.drawable.meun_call)),
HomeFragment.class, null);
tabHost.getTabWidget().setDividerDrawable(
getResources().getDrawable(R.drawable.border));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.transparent));
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT, 1f);
tabHost.getTabWidget().getChildAt(i).setLayoutParams(params);
tabHost.getTabWidget().getChildAt(i).setPadding(0, 0, 0, 0);
tabHost.getTabWidget().getChildAt(i).setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_UP) {
Log.d("test1",""+v.getTag());
return true; // doesnt allow tab change
}
return false;
}
});
}
您可以找到返回null的行Log.d("test1",""+v.getTag());
。预计会返回一些像#34; home&#34; ,&#34;表格&#34;等等.....非常感谢
答案 0 :(得分:1)
因为您没有为 newTabSpec 的查看设置任何标记。您设置了可绘制图标,但未设置任何标记。所以你可以用两种方式做到这一点:
1)首先从可绘制的图标中创建 imageView :
imageView.setImageBitmap(bitmap);
imageView.setImageResource(R.drawable.my_image);
imageView.setImageDrawable(drawable);
然后将标记设置为 imageView ,并使用setIndicator(View view)
将其添加到 newTabSpec 。
2)或者在添加drawable之后,您可以使用 getChildTabViewAt()来获取视图,然后为其设置标记。
总结一下,你没有设置任何标签,所以它显然是空的。
文件说:TabHost.TabSpec:
标签包含标签指示符,内容和用于保留的标记 追踪它。此构建器可帮助您选择这些选项。为了 选项卡指示器,您的选择是:1)设置标签2)设置标签和 icon对于选项卡内容,
所以字符串只是一个标签,tag
和标签是两个不同的东西,tag
是view
的记忆,你可以存储任何object
对象可以是string
或其他任何像ViewHolder设计模式,用于创建列表视图。
答案 1 :(得分:1)
以下是最后一位作者推荐的解决方案2):
View vv = tabWidget.getChildAt(i);
vv.setTag("mytag_"+i);