无法从viewpager中的片段访问资源

时间:2017-07-01 14:53:34

标签: android fragment

这里我想在android中创建一个饼图,而不是我想要使用图像的数据的标签。但问题是我无法从我的片段访问drawables。如果我通过NullPointerException()致电getResources(),则会抛出getActivity().getApplicationContext()。 该片段位于FragmentPagerAdapter下。

public class MonitorOverallFragment extends Fragment {
    private Context mContext;
    private Activity mActivity;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    public MonitorOverallFragment(){

    }

    int [] sampledata = {30, 40, 20, 10};
    Bitmap[] icons1 = {BitmapFactory.decodeResource(getContext().getResources(),
            R.drawable.ic_card_analitics_white),
            BitmapFactory.decodeResource(getContext().getResources(),
                    R.drawable.ic_kredit_analitics_white),
            BitmapFactory.decodeResource(getContext().getResources(),
            R.drawable.ic_vklad_analitics_white),
            BitmapFactory.decodeResource(getContext().getResources(),
            R.drawable.ic_nps_analitics_white)};
    private String icons[] = {"a", "b", "c", "d"};



    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_monitor_overall, container, false);

        setUpPieChart(rootView);
        return  rootView;
    }
    private void setUpPieChart(View v){
        List<PieEntry> pieEntries = new ArrayList<>();
        for(int i = 0; i<sampledata.length; i++){
            pieEntries.add(new PieEntry(sampledata[i], icons1[i]));
        }
        PieDataSet dataSet = new PieDataSet(pieEntries, "Expenditures");
        dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        PieData data = new PieData(dataSet);

        PieChart chart = (PieChart)v.findViewById(R.id.pie_monitor_overall);
        chart.setData(data);
        chart.invalidate();

    }
}

我的适配器:

    public class MonitoringPagerAdapter extends FragmentPagerAdapter{

        public MonitoringPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){

                case 0:
                    return new Registration1Fragment();
                case 1:
                    return new FilialFragment();
                case 2:
                    return new MonitorOverallFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }
        @Override
        public CharSequence getPageTitle(int position) {
            String postuplenie =getResources().getString(R.string.tab_postupleniya);
            String rasxod =getResources().getString(R.string.tab_expenditures);
            String overall = getResources().getString(R.string.tab_overall);
            switch (position) {
                case 0:
                    return postuplenie;
                case 1:
                    return rasxod;
                case 2:
                    return overall;
            }
            return null;
        }
    }

}

活动类:

public class MonitoringActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitoring);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        MonitoringPagerAdapter monitoringPagerAdapter = new MonitoringPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        ViewPager mViewPager = (ViewPager) findViewById(R.id.monitoring_pager);
        mViewPager.setAdapter(monitoringPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.monitoring_tabs);
        tabLayout.setupWithViewPager(mViewPager);
    }
}

1 个答案:

答案 0 :(得分:1)

你没有指明你的Exception发生在哪里,但我假设它在这里:

Bitmap[] icons1 = {
    BitmapFactory.decodeResource(getContext().getResources(),R.drawable.ic_card_analitics_white),
    BitmapFactory.decodeResource(getContext().getResources(),R.drawable.ic_kredit_analitics_white),
    BitmapFactory.decodeResource(getContext().getResources(),R.drawable.ic_vklad_analitics_white),
    BitmapFactory.decodeResource(getContext().getResources(),R.drawable.ic_nps_analitics_white)
};
首次创建getContext()时,

null将返回Fragment,并且最早不会返回有效Context,直到onAttach()。将icons1的分配移动到以后的生命周期回调(即onCreateView()),您应该没问题。