在自学黑马项目视频--短信智能管理器, 主布局是使用TabHost进行布局,明明看完视频,自己再敲代码,没问题,却总是没有图标。
关键代码:
private TabHost mTabHost;
private void initTabHost() { addTabSpec("conversation","会话",R.mipmap.tab_conversation,new Intent(this,ConversactionUI.class)); addTabSpec("folder","文件夹",R.mipmap.tab_folder,new Intent(this,FolderUI.class)); addTabSpec("group","群组",R.mipmap.tab_group,new Intent(this,GroupUI.class)); } private void addTabSpec(String tab , String label , int icon , Intent intent) { TabHost.TabSpec tabSpec = mTabHost.newTabSpec(tab); tabSpec.setIndicator(label, getResources().getDrawable(icon)); tabSpec.setContent(intent); mTabHost.addTab(tabSpec); }
明明代码写得很具有条理性,可还是不出现图标,经过百度,谷歌, stackoverflow ,得到解决:
为什么代码对的,却显示不出图标:
SDK 4.03以下, 只有页签标题可以显示,进过测试,果然如此!
解决方法:
把页签标题设置为空字符串,就可以显示图标,但是对设计界面效果并不是很多,不推荐, 那么既然要显示图标,也要显示页签标题,那只有一个办法就是自定义页签
函数多态:public TabHost.TabSpec setIndicator(CharSequence label, Drawable icon) { throw new RuntimeException("Stub!"); } public TabHost.TabSpec setIndicator(View view) { throw new RuntimeException("Stub!"); }我们直接使用第二个方法,来进行自定义页签,
View tabIndicator = LayoutInflater.from(this).inflate(你的页签view‘id getTabWidget(), false);
setIndicator(tabIndicator);
由于并不是很难,所以只写了关键代码,只为了记录, 如看不懂,请多看书!