访问资源的Android异常

时间:2017-12-18 10:26:07

标签: android

我在第1414行从片段中获得了异常。

java.lang.IllegalStateException: Fragment HomeFragment{2104037} not attached to Activity
                                                                               at android.support.v4.app.Fragment.getResources(Fragment.java:715)
                                                                               at com.juarezserver.citystatus.fragment.HomeFragment.addMarker(HomeFragment.java:1414)

这是涉及的一段代码:

if (tiporeporte.equals("1")){

            int height = 75;
            int width = 75;
            BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.tipo_1);//line 1414
            Bitmap b=bitmapdraw.getBitmap();
            Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);


            markerOptions.icon(BitmapDescriptorFactory.fromBitmap(smallMarker));
        }

我不知道我做错了什么。

3 个答案:

答案 0 :(得分:0)

我认为问题在于:

BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.tipo_1);

您尝试通过 getResources()访问资源,但您的片段尚未附加。

尝试在Fragment的onAttache()或Fragment活动准备就绪的任何其他生命周期事件中调用该代码块。

请查看Fragment的生命周期:https://developer.android.com/guide/components/fragments.html

答案 1 :(得分:0)

您尝试在将片段附加到活动之前调用
(BitmapDrawable)getResources().getDrawable(R.drawable.tipo_1);//line 1414。首先等待Fragment附加一个活动,然后你可以调用yourConvertView.getResources().***你的转化视图是你在片段的OnCreateView()得到的视图


更新
这可能对某人有所帮助 更换了

(BitmapDrawable)getResources().getDrawable(R.drawable.tipo_1);//line 1414


markerOptions.icon(BitmapDescriptorFactory.fromResource(R.dr‌​awable.tipo_1));

并且工作

答案 2 :(得分:0)

我尝试改变获取drawable的方式,问题就消失了。

if (tiporeporte.equals("1")){

            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.tipo_1));
        }