这是我创建标签主机的方法,我想做的是在用户单击标签时获取标签。问题是,它返回 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());
。预期会返回一些字符串,如“home”、“form”等......非常感谢
最佳答案
因为您没有为 newTabSpec 的View 设置任何标签。您设置了可绘制图标,但没有设置任何标签。所以你可以通过两种方式做到这一点:
1) 首先从您的可绘制图标创建一个imageView:
imageView.setImageBitmap(bitmap);
imageView.setImageResource(R.drawable.my_image);
imageView.setImageDrawable(drawable);
然后将 Tag 设置为您的 imageView 并使用 setIndicator(View view)
将其添加到您的 newTabSpec.
2) 或者在添加可绘制对象后,您可以使用getChildTabViewAt() 获取 View ,然后为其设置标签。
总而言之,您没有设置任何标签,因此它显然是空的。
文档说:
TabHost.TabSpec:
A tab has a tab indicator, content, and a tag that is used to keep track of it. This builder helps choose among these options. For the tab indicator, your choices are: 1) set a label 2) set a label and an icon For the tab content,
所以字符串只是一个标签,tag
和标签是两个不同的东西,tag
是你对 view
的内存可以在其中存储任何对象
,该对象可以是字符串
或任何其他用于创建 ListView 的ViewHolder设计模式。
关于android - 当我获取选项卡的标签时,FragmentTabHost 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25970477/