无法使用字符串作为选项卡名称

时间:2015-06-24 15:21:56

标签: java android android-activity android-tabactivity

我正在学习本教程,并希望将字符串资源用于我的标签名称,但显然我在本教程中无法做到这一点。有人知道这个吗?

    public class MainActivity extends ActionBarActivity {

    // Declaring Your View and Variables

    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"Home","Events"};
    int Numboftabs =2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Creating The Toolbar and setting it as the Toolbar for the activity

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);
    }
}

Android Sliding Tabs with Material Design | Exoguru

2 个答案:

答案 0 :(得分:2)

要在de FragmentStatePagerAdapter中使用String资源,您需要一个Context,因此您需要更改类的构造函数并传递Context。

public ViewPagerAdapter(FragmentManager fm, int mNumbOfTabsumb, Context context) {
        super(fm);
        this.NumbOfTabs = mNumbOfTabsumb;
        this.context = context;

    }

因此,在getPageTitle中,您无需返回Titles[position]

您可以这样做:

@Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case FRAGMENT_1:
                return context.getResources().getString(R.string.some_string);
        }
        return super.getPageTitle(position);
    }

FRAGMENT_1是该类的常量。 如果你不再使用你的标题,你可以从构造函数中删除它,因为我删除了它。

答案 1 :(得分:0)

将文本文件放在assets文件夹中,其中包含您要使用的标题。

获取文件:

AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("helloworld.txt");

使用InputStream读取文件(谷歌获取模板)

阅读时,请执行以下操作:

CharSequence Titles[] = new CharSequence[2];
int index = 0;
while(textFile.hasNext() && index < Titles.length){
    String lineInTextFile = textFile.next();
    Titles[index] = lineInTextFile;
    index++;
}