I trying to set the title for my viewpager, I can't seem to get it to work. I tried Resources.getSystem().getString(R.string.title1); and also tried to pass a context. Could anyone help me?
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public Fragment getItem(int position) {
return PageFragment.create(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return Resources.getSystem().getString(R.string.title1);
case 1:
return Resources.getSystem().getString(R.string.title1);
case 2:
return Resources.getSystem().getString(R.string.title1);
}
return null;
}
}
Logcat:
09-02 17:40:33.160: E/AndroidRuntime(3116): FATAL EXCEPTION: main
09-02 17:40:33.160: E/AndroidRuntime(3116): android.content.res.Resources$NotFoundException: String resource ID #0x7f050003
09-02 17:40:33.160: E/AndroidRuntime(3116): at android.content.res.Resources.getText(Resources.java:230)
09-02 17:40:33.160: E/AndroidRuntime(3116): at android.content.res.Resources.getString(Resources.java:314)
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code in build. gradle. Step 3 − Add the following code to res/layout/activity_main.
You can create swipe views using AndroidX's ViewPager widget. To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .
ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in app. It is a widget found in the support library. To use it you'll have to put the element inside your XML layout file that'll contain multiple child views.
you should call getString from an activity's context, change your code to
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
Context context;
public ViewPagerAdapter(FragmentManager fm, Context nContext) {
super(fm);
context = nContext;
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public Fragment getItem(int position) {
return PageFragment.create(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return context.getString(R.string.title1);
case 1:
return context.getString(R.string.title1);
case 2:
return context.getString(R.string.title1);
}
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With