我正在关注来自Google Android开发人员频道的this指令视频,以创建一个包含标签的简单应用。
不幸的是在放置代码时:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.content_pager);
PagerAdapter pagerAdapter = new ContentPager(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.content_tabs);
tabLayout.setupWithViewPager(viewPager);
...
进入我的MainActivitys onCreate我收到异常消息:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.smilingkoala.ping/com.smilingkoala.ping.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x7f080050
请求的资源是否仍然不可用,我只需要在其他地方实例化ViewPager,或者我是否犯了一些基本错误?
编辑 - 在@Chol评论后找到解决方案。旧代码下面: ContetnPager的结构主体如下所示
public ContentPager(FragmentManager fm) {
super(fm);
}
使用getPageTitle方法:
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return Resource.getSystem().getString(R.string.pings_page_title);
case 1:
return Resources.getSystem().getString(R.string.contacts_page_title);
default:
return null;
}
}
答案 0 :(得分:0)
我的解决方案(感谢@Chol的评论)
将ContentPager构造函数更改为:
public ContentPager(FragmentManager fm, Context m_context) {
super(fm);
context = m_context;
}
和getPageTitle方法:
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return context.getResources().getString(R.string.pings_page_title);
case 1:
return context.getResources().getString(R.string.contacts_page_title);
default:
return null;
}
}
将onCreate中的代码更改为:
ViewPager viewPager = (ViewPager) findViewById(R.id.content_pager);
PagerAdapter pagerAdapter = new ContentPager(getSupportFragmentManager(), this);
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.content_tabs);
tabLayout.setupWithViewPager(viewPager);
答案 1 :(得分:0)
只需像这样更新:
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return String.valueOf(context.getResources().getString(R.string.pings_page_title));
case 1:
return String.valueOf(context.getResources().getString(R.string.contacts_page_title));
default:
return "";
}
}