簡體   English   中英

在FragmentStatePagerAdapter中顯示Android Toast消息

[英]Display Android Toast message in FragmentStatePagerAdapter

我試圖在FragmentStatePagerAdapter顯示吐司消息,但失敗了。

我需要獲取上下文以插入我的代碼

Toast.makeText(, "The message", Toast.LENGTH_SHORT).show();

但是我不能使用getContext()getActivity()因為我沒有任何onCreateView方法,而且我不知道任何其他獲取上下文的方法。

這是我的FragmentStatePagerAdapter代碼:

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.widget.Toast;

import com.mobaleghan.tablighcalendar.view.fragment.PrayerListViewContainerFragment;
import com.mobaleghan.tablighcalendar.view.fragment.TablighDataTabFragment;

public class TabbedKnowledgeAdapter extends FragmentStatePagerAdapter {

    private int mNumOfTabs;
    private TabLayout tabLayout;

    public TabbedKnowledgeAdapter(FragmentManager fm, int NumOfTabs, TabLayout tabLayout) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
        this.tabLayout = tabLayout;

    }

    @Override
    public Fragment getItem(int position) {

        //Some codes

        Toast.makeText(, "the message", Toast.LENGTH_SHORT).show(); //I need context

        //Some other codes

    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

那么,如何在FragmentStatePagerAdapter獲取上下文?

您可以使用:

tabLayout.getContext();

在構造函數中傳遞上下文

Context context;
public TabbedKnowledgeAdapter(FragmentManager fm, Context ctx, int NumOfTabs, TabLayout tabLayout) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
    this.tabLayout = tabLayout;
    this.context = ctx;

}

並在您的Toast中傳遞此上下文。

使用應用程序的上下文

例如

@Override
public Fragment getItem(int position) {

    //Some codes

    Toast.makeText(((SampleApplication)getApplication()).getApplicationContext(), "the message", Toast.LENGTH_SHORT).show(); //I need context

    //Some other codes

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM