In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray[] = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
Context
objects in Android. It can lead to memory leaks. See my answer for a less risky solution. – Cohbert