在FragmentStatePagerAdapter中显示Android Toast消息

时间:2017-12-23 08:47:47

标签: android android-context fragmentstatepageradapter

我试图在FragmentStatePagerAdapter中显示一个Toast留言,但我失败了。

我需要在我的代码中插入上下文

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中获取上下文?

3 个答案:

答案 0 :(得分:0)

您可以使用:

<?php
// This is to check if the request is coming from a specific URL
$ref = $_SERVER['HTTP_REFERER'];

if($ref !== 'http://example.com/1.php') {
  header('Location: 1.php');
   //Alternates as necessary
  // header('Location: /directory/1.php');
 //header('Location: http://example.com/1.php');
  exit;
}

//Your code if from 1.php
?>

答案 1 :(得分:-1)

在构造函数中传递上下文

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

}

并在你的Toast中传递这个背景。

答案 2 :(得分:-1)

使用应用程序的上下文

例如

@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

}