问题描述:
- 在研究菜鸟商城项目源码的时候,其中使用FragmentTabHost+fragment实现底部菜单,其用法有关键三点:1、Activity 要继承FragmentActivity;2、调用setup() 方法;3、添加TabSpec。在这过程中,发现定义的的一个Tab类中,title明明是定义为int类型,但是在new Tab()时,传入的是R.string.home竟然不报错,而我以为R.string.home是string类型的啊,这怎么会不报错呢 ? 后来才知道其中的原理,那就是java编译的的时候会把string类型变量存放在栈的临时变量表中,并给出一个int类型的ID指向此变量。并且,因为底部菜单是由图标和文字组成,就需要使用到string类型的文本,所以,通过getString( )方法,因为getString( ) 方法底层实现过程有一句“Resource id for the string”,也就是说,并不是将int类型转换成string类型,而是通过id获取到相关的string数据资源。
public class Tab {
private int title;
private int icon;
private Class fragment;
public Tab(Class fragment,int title, int icon) {
this.title = title;
this.icon = icon;
this.fragment = fragment;
}
Tab tab_home = new Tab(HomeFragment.class,R.string.home,R.drawable.selector_icon_home);
TabHost.TabSpec tabSpec = mTabhost.newTabSpec(getString(tab.getTitle()));
/**
* Returns a localized string from the application's package's
* default string table.
*
* @param resId Resource id for the string
* @return The string data associated with the resource, stripped of styled
* text information.
*/
@NonNull
public final String getString(@StringRes int resId) {
return getResources().getString(resId);
}